- Python MongoDB 教程
- Python MongoDB - 首页
- Python MongoDB - 简介
- Python MongoDB - 创建数据库
- Python MongoDB - 创建集合
- Python MongoDB - 插入文档
- Python MongoDB - 查找
- Python MongoDB - 查询
- Python MongoDB - 排序
- Python MongoDB - 删除文档
- Python MongoDB - 删除集合
- Python MongoDB - 更新
- Python MongoDB - 限制
- Python MongoDB 有用资源
- Python MongoDB - 快速指南
- Python MongoDB - 有用资源
- Python MongoDB - 讨论
Python MongoDB - 快速指南
Python MongoDB - 简介
Pymongo 是一个 Python 发行版,提供用于处理 MongoDB 的工具,它是从 Python 连接到 MongoDB 数据库的首选方式。
安装
要安装 pymongo,首先确保您已正确安装 python3(以及 PIP)和 MongoDB。然后执行以下命令。
C:\WINDOWS\system32>pip install pymongo Collecting pymongo Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl Installing collected packages: pymongo Successfully installed pymongo-3.9.0
验证
安装 pymongo 后,打开一个新的文本文档,将以下行粘贴到其中,并将其保存为 test.py。
import pymongo
如果您已正确安装 pymongo,如果按照以下所示执行 test.py,则不应该出现任何问题。
D:\Python_MongoDB>test.py D:\Python_MongoDB>
Python MongoDB - 创建数据库
与其他数据库不同,MongoDB 没有提供单独的命令来创建数据库。
通常,use 命令用于选择/切换到特定的数据库。此命令首先验证我们指定的数据库是否存在,如果存在,则连接到它。如果我们使用 use 命令指定的数据库不存在,则会创建一个新的数据库。
因此,您可以使用 use 命令在 MongoDB 中创建数据库。
语法
use DATABASE 语句的基本语法如下:
use DATABASE_NAME
示例
以下命令创建一个名为 mydb 的数据库。
>use mydb switched to db mydb
您可以使用 db 命令验证您的创建,这将显示当前数据库。
>db mydb
使用 Python 创建数据库
要使用 pymongo 连接到 MongoDB,您需要导入并创建一个 MongoClient,然后您可以直接访问您需要在属性 passion 中创建的数据库。
示例
以下示例在 MangoDB 中创建一个数据库。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........") #Verification print("List of databases after creating new one") print(client.list_database_names())
输出
Database created........ List of databases after creating new one: ['admin', 'config', 'local', 'mydb']
您还可以在创建 MongoClient 时指定端口和主机名,并以字典样式访问数据库。
示例
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........")
输出
Database created........
Python MongoDB - 创建集合
MongoDB 中的集合保存一组文档,类似于关系数据库中的表。
您可以使用 createCollection() 方法创建集合。此方法接受一个表示要创建的集合名称的字符串值和一个可选参数 options。
使用它,您可以指定以下内容:
集合的 大小。
带限制的集合中允许的最大 数量 的文档。
我们创建的集合是否应该是带限制的集合(固定大小的集合)。
我们创建的集合是否应该自动建立索引。
语法
以下是创建 MongoDB 集合的语法。
db.createCollection("CollectionName")
示例
以下方法创建一个名为 ExampleCollection 的集合。
> use mydb switched to db mydb > db.createCollection("ExampleCollection") { "ok" : 1 } >
同样,以下是一个使用 createCollection() 方法的选项创建集合的查询。
>db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } ) { "ok" : 1 } >
使用 Python 创建集合
以下 Python 示例连接到 MongoDB 中的数据库(mydb),并在其中创建一个集合。
示例
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection collection = db['example'] print("Collection created........")
输出
Collection created........
Python MongoDB - 插入文档
您可以使用 insert() 方法将文档存储到 MongoDB 中。此方法接受 JSON 文档作为参数。
语法
以下是 insert 方法的语法。
>db.COLLECTION_NAME.insert(DOCUMENT_NAME)
示例
> use mydb switched to db mydb > db.createCollection("sample") { "ok" : 1 } > doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} { "name" : "Ram", "age" : "26", "city" : "Hyderabad" } > db.sample.insert(doc1) WriteResult({ "nInserted" : 1 }) >
同样,您还可以使用 insert() 方法插入多个文档。
> use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ {"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"}, {"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"}, {"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) >
使用 Python 创建集合
Pymongo 提供了一个名为 insert_one() 的方法来在 MangoDB 中插入文档。对于此方法,我们需要以字典格式传递文档。
示例
以下示例在名为 example 的集合中插入一个文档。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} coll.insert_one(doc1) print(coll.find_one())
输出
{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
要使用 pymongo 将多个文档插入 MongoDB,您需要调用 insert_many() 方法。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") print(res.inserted_ids)
输出
Data inserted ...... ['101', '102', '103']
Python MongoDB - 查找
您可以使用 find() 方法读取/检索 MongoDB 中存储的文档。此方法以非结构化的方式检索并显示 MongoDB 中的所有文档。
语法
以下是 find() 方法的语法。
>db.COLLECTION_NAME.find()
示例
假设我们已使用以下查询将 3 个文档插入名为 testDB 的数据库中的名为 sample 的集合中:
> use testDB > db.createCollection("sample") > data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] > db.sample.insert(data)
您可以使用 find() 方法检索插入的文档,如下所示:
> use testDB switched to db testDB > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } >
您还可以使用 findOne() 方法检索集合中的第一个文档,如下所示:
> db.sample.findOne() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
使用 Python 检索数据 (find)
pymongo 的 find_One() 方法用于根据您的查询检索单个文档,如果没有任何匹配项,此方法将不返回任何内容,如果您不使用任何查询,它将返回集合的第一个文档。
当您只需要检索一个结果文档或确定您的查询仅返回一个文档时,此方法非常方便。
示例
以下 Python 示例检索集合的第一个文档:
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydatabase'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") print(res.inserted_ids) #Retrieving the first record using the find_one() method print("First record of the collection: ") print(coll.find_one()) #Retrieving a record with is 103 using the find_one() method print("Record whose id is 103: ") print(coll.find_one({"_id": "103"}))
输出
Data inserted ...... ['101', '102', '103'] First record of the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} Record whose id is 103: {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
要在一个查询中获取多个文档(find 方法的单次调用),您可以使用 pymongo 的 find() 方法。如果没有传递任何查询,它将返回集合的所有文档,如果您已将查询传递给此方法,它将返回所有匹配的文档。
示例
#Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Records of the collection: ") for doc1 in coll.find(): print(doc1) #Retrieving records with age greater than 26 using the find() method print("Record whose age is more than 26: ") for doc2 in coll.find({"age":{"$gt":"26"}}): print(doc2)
输出
Data inserted ...... Records of the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Record whose age is more than 26: {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Python MongoDB - 查询
在使用 find() 方法检索时,您可以使用查询对象过滤文档。您可以将指定所需文档条件的查询作为参数传递给此方法。
运算符
以下是 MongoDB 查询中使用的运算符列表。
操作 | 语法 | 示例 |
---|---|---|
等于 | {"key" : "value"} | db.mycol.find({"by":"tutorials point"}) |
小于 | {"key" :{$lt:"value"}} | db.mycol.find({"likes":{$lt:50}}) |
小于等于 | {"key" :{$lte:"value"}} | db.mycol.find({"likes":{$lte:50}}) |
大于 | {"key" :{$gt:"value"}} | db.mycol.find({"likes":{$gt:50}}) |
大于等于 | {"key" {$gte:"value"}} | db.mycol.find({"likes":{$gte:50}}) |
不等于 | {"key":{$ne: "value"}} | db.mycol.find({"likes":{$ne:50}}) |
示例1
以下示例检索名称为 sarmista 的集合中的文档。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['sdsegf'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving data print("Documents in the collection: ") for doc1 in coll.find({"name":"Sarmista"}): print(doc1)
输出
Data inserted ...... Documents in the collection: {'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
示例2
以下示例检索集合中年龄值大于 26 的文档。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['ghhj'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving data print("Documents in the collection: ") for doc in coll.find({"age":{"$gt":"26"}}): print(doc)
输出
Data inserted ...... Documents in the collection: {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Python MongoDB - 排序
在检索集合内容时,您可以使用 sort() 方法对它们进行排序并按升序或降序排列。
对于此方法,您可以传递字段和排序顺序(1 或 -1)。其中,1 表示升序,-1 表示降序。
语法
以下是 sort() 方法的语法。
>db.COLLECTION_NAME.find().sort({KEY:1})
示例
假设我们已创建一个集合并向其中插入了 5 个文档,如下所示:
> use testDB switched to db testDB > db.createCollection("myColl") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
以下行检索集合中的所有文档,这些文档根据年龄按升序排序。
> db.sample.find().sort({age:1}) { "_id" : "1005", "name" : "Sarmista", "age" : 23, "city" : "Delhi" } { "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" } { "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
使用 Python 对文档进行排序
要按升序或降序对查询结果进行排序,pymongo 提供了 sort() 方法。为此方法传递一个数字值,表示您需要的结果中的文档数量。
默认情况下,此方法根据指定的字段按升序对文档进行排序。如果您需要按降序排序,请将 -1 与字段名称一起传递:
coll.find().sort("age",-1)
示例
以下示例检索集合中的所有文档,并根据年龄值按升序排列:
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['b_mydb'] #Creating a collection coll = db['myColl'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving first 3 documents using the find() and limit() methods print("List of documents (sorted in ascending order based on age): ") for doc1 in coll.find().sort("age"): print(doc1)
输出
Data inserted ...... List of documents (sorted in ascending order based on age): {'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'} {'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'} {'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'} {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Python MongoDB - 删除文档
您可以使用 MongoDB 的 remove() 方法删除集合中的文档。此方法接受两个可选参数:
删除条件,指定删除文档的条件。
仅一个,如果您将 true 或 1 作为第二个参数传递,则只会删除一个文档。
语法
以下是 remove() 方法的语法:
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
示例
假设我们已创建一个集合并向其中插入了 5 个文档,如下所示:
> use testDB switched to db testDB > db.createCollection("myColl") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
以下查询删除名称值为 Sarmista 的集合中的文档。
> db.sample.remove({"name": "Sarmista"}) WriteResult({ "nRemoved" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } { "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" } { "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
如果您在不传递删除条件的情况下调用 remove() 方法,则集合中的所有文档都将被删除。
> db.sample.remove({}) WriteResult({ "nRemoved" : 5 }) > db.sample.find()
使用 Python 删除文档
要从 MangoDB 的集合中删除文档,您可以使用 delete_one() 和 delete_many() 方法从集合中删除文档。
这些方法接受一个查询对象,指定删除文档的条件。
detele_one() 方法删除单个文档(如果匹配)。如果没有指定查询,此方法将删除集合中的第一个文档。
示例
以下 Python 示例删除 id 值为 1006 的集合中的文档。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['lpaksgf'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Deleting one document coll.delete_one({"_id" : "1006"}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2)
输出
Data inserted ...... Documents in the collection after update operation: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} {'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'} {'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
同样,pymongo 的 delete_many() 方法将删除满足指定条件的所有文档。
示例
以下示例删除集合中年龄值大于 26 的所有文档:
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['sampleDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Deleting multiple documents coll.delete_many({"age":{"$gt":"26"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2)
输出
Data inserted ...... Documents in the collection after update operation: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'} {'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'} {'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}
如果您在不传递任何查询的情况下调用 delete_many() 方法,则此方法将删除集合中的所有文档。
coll.delete_many({})
Python MongoDB - 删除集合
您可以使用 MongoDB 的 drop() 方法删除集合。
语法
以下是 drop() 方法的语法:
db.COLLECTION_NAME.drop()
示例
以下示例删除名称为 sample 的集合:
> show collections myColl sample > db.sample.drop() true > show collections myColl
使用 Python 删除集合
您可以通过调用 drop() 方法删除/删除当前数据库中的集合。
示例
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['example2'] #Creating a collection col1 = db['collection'] col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"}) col2 = db['coll'] col2.insert_one({"name": "Rahim", "age": "27", "city": "Bangalore"}) col3 = db['myColl'] col3.insert_one({"name": "Robert", "age": "28", "city": "Mumbai"}) col4 = db['data'] col4.insert_one({"name": "Romeo", "age": "25", "city": "Pune"}) #List of collections print("List of collections:") collections = db.list_collection_names() for coll in collections: print(coll) #Dropping a collection col1.drop() col4.drop() print("List of collections after dropping two of them: ") #List of collections collections = db.list_collection_names() for coll in collections: print(coll)
输出
List of collections: coll data collection myColl List of collections after dropping two of them: coll myColl
Python MongoDB - 更新
您可以使用 update() 方法或 save() 方法更新现有文档的内容。
update 方法修改现有文档,而 save 方法用新文档替换现有文档。
语法
以下是 MangoDB 的 update() 和 save() 方法的语法:
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) Or, db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
示例
假设我们在数据库中创建了一个集合,并在其中插入了 3 条记录,如下所示:
> use testdatabase switched to db testdatabase > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, ... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ {"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"}, {"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"}, {"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"} ] > db.createCollection("sample") { "ok" : 1 } > db.sample.insert(data)
以下方法更新 id 为 1002 的文档的 city 值。
>db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
同样,您可以使用相同 id 保存新数据来替换文档。
> db.sample.save({ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
使用 python 更新文档
类似于检索单个文档的 find_one() 方法,pymongo 的 update_one() 方法更新单个文档。
此方法接受一个查询,指定要更新的文档和更新操作。
示例
以下 Python 示例更新集合中文档的 location 值。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2)
输出
Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
类似地,pymongo 的update_many() 方法更新满足指定条件的所有文档。
示例
以下示例更新集合中所有文档(空条件)的位置值:
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_many({},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2)
输出
Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}
Python MongoDB - 限制
在检索集合内容时,您可以使用 limit() 方法限制结果中的文档数量。此方法接受一个数字值,表示您希望结果中包含的文档数量。
语法
以下是 limit() 方法的语法:
>db.COLLECTION_NAME.find().limit(NUMBER)
示例
假设我们已创建一个集合并向其中插入了 5 个文档,如下所示:
> use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
以下代码行检索集合中的前 3 个文档。
> db.sample.find().limit(3) { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
使用 Python 限制文档
为了将查询结果限制到特定数量的文档,pymongo 提供了limit() 方法。为此方法传递一个数字值,表示您需要结果中包含的文档数量。
示例
以下示例检索集合中的前三个文档。
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['l'] #Creating a collection coll = db['myColl'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving first 3 documents using the find() and limit() methods print("First 3 documents in the collection: ") for doc1 in coll.find().limit(3): print(doc1)
输出
Data inserted ...... First 3 documents in the collection: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}