Python Mongodb 简明教程
Python MongoDB - Introduction
Pymongo是一个python发行版,提供了与MongoDB一起使用的工具,它是从python与MongoDB数据库进行通信的首选方式。
Installation
要安装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
Python MongoDB - Create Database
与其他数据库不同的是,MongoDB 没有提供单独用于创建数据库的命令。
一般来说,use 命令用于选择/切换到指定的数据库。此命令最初会验证我们指定的数据库是否存在,如果存在,则会连接到该数据库。如果我们使用 use 命令指定的数据库不存在,则会创建一个新数据库。
因此,你可以在 MongoDB 中使用 @[s0] 命令创建一个数据库。
Example
以下命令创建一个名为 mydb 的数据库。
>use mydb
switched to db mydb
你可以使用 db 命令验证你的创建操作,该命令会显示当前的数据库。
>db
mydb
Creating Database Using Python
要在使用 pymongo 连接到 MongoDB,你需要导入并创建一个 MongoClient,然后你可以直接访问你需要在属性 passion 中创建的数据库。
Example
以下示例在 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())
Output
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
你还可以创建 MongoClient 时指定端口和主机名,并可以使用字典风格访问数据库。
Python MongoDB - Create Collection
MongoDB中的集合包含一组文档,它类似于关系数据库中的表。
您可以使用 createCollection() 方法创建集合。此方法接受一个表示要创建的集合的名称的字符串值和一个选项(可选)参数。
使用此选项可以指定以下内容−
-
集合的大小。
-
截断集合中允许的最大文档数。
-
我们创建的集合应为截断集合(固定大小集合)。
-
我们创建的集合应为自动索引。
Example
以下方法创建一个名为 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 }
>
Creating a Collection Using Python
以下 Python 示例连接到 MongoDB 中的数据库 (mydb),并在其中创建一个集合。
Python MongoDB - Insert Document
你可以使用 insert() 方法将文档存储到 MongoDB 中。此方法接收 JSON 文档作为参数。
Example
> 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" : [ ]
})
>
Creating a Collection Using Python
Pymongo 提供了一个名为 insert_one() 的方法来在 MangoDB 中插入文档。对于此方法,我们需要以字典格式传递文档。
Example
以下示例在名为 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())
Output
{'_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)
Python MongoDB - Find
您可以使用 find() 方法读/取从 MongoDB 中存储的文档。此方法以非结构化方式检索和显示 MongoDB 中的所有文档。
Example
假设我们已使用以下查询将 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" }
Retrieving Data (find) Using Python
pymongo 的 find_One() 方法用于根据您的查询检索单个文档,如果没有匹配项,此方法将不返回任何内容,如果您未使用任何查询,它将返回集合的第一个文档。
每当您需要仅检索结果中的一个文档或确信您的查询只返回一个文档时,此方法都派上用场。
Example
以下 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"}))
Output
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() 方法。如果没有传递任何查询,它将返回集合的所有文档,如果您已将查询传递给此方法,它将返回所有匹配的文档。
Example
#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)
Output
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 - Query
在使用 find() 方法检索时,您可以使用查询对象过滤文档。您可以将指定所需文档条件的查询作为参数传递给此方法。
Operators
以下是 MongoDB 中查询中使用的运算符列表。
Operation |
Syntax |
Example |
Equality |
{"key" : "value"} |
db.mycol.find({"by":"tutorials point"}) |
Less Than |
{"key" :{$lt:"value"}} |
db.mycol.find({"likes":{$lt:50}}) |
Less Than Equals |
{"key" :{$lte:"value"}} |
db.mycol.find({"likes":{$lte:50}}) |
Greater Than |
{"key" :{$gt:"value"}} |
db.mycol.find({"likes":{$gt:50}}) |
Greater Than Equals |
{"key" {$gte:"value"}} |
db.mycol.find({"likes":{$gte:50}}) |
Not Equals |
{"key":{$ne: "value"}} |
db.mycol.find({"likes":{$ne:50}}) |
Example1
以下示例检索名称为 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)
Output
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
Example2
以下示例检索 age 值大于 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)
Python MongoDB - Sort
在检索集合内容时,您可以使用 sort() 方法按升序或降序对它们进行排序和排列。
您可以将字段和排序顺序(1 或 -1)传递给此方法。其中,1 表示升序,-1 表示降序。
Example
假设我们已经创建了一个集合,并在其中插入了 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" }
Sorting the Documents Using Python
为了按升序或降序对查询结果进行排序,pymongo 提供了 sort() 方法。向此方法传递一个数字值,表示结果中所需文档的数量。
默认情况下,此方法根据指定字段将文档按升序排序。如果您需要按降序排序,则传递 -1 以及字段名称:
coll.find().sort("age",-1)
Example
以下示例按升序根据年龄值排列检索集合的所有文档:
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)
Output
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 - Delete Document
您可以使用 MongoDB 的 remove() 方法来删除集合中的文档。此方法接受两个可选参数:
-
删除标准规定了删除文档的条件。
-
只需一条,如果你将真值或 1 作为第二个参数,则只会删除一个文档。
Example
假设我们已经创建了一个集合,并在其中插入了 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" : [ ]
})
以下查询将删除具有 name 值为 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()
Deleting Documents Using Python
要从 MangoDB 的集合中删除文档,你可以使用 delete_one() 和 delete_many() 方法从集合中删除文档。
这些方法接受一个查询对象来指定删除文档的条件。
detete_one() 方法删除单个文档(如果匹配)。如果未指定查询,则此方法将删除集合中的第一个文档。
Example
以下 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)
Output
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() 方法删除满足指定条件的所有文档。
Example
以下示例删除了集合中 age 值大于 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)
Output
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 - Drop Collection
你可以使用 MongoDB 的 drop() 方法删除集合。
Example
以下示例删除名为 sample 的集合:
> show collections
myColl
sample
> db.sample.drop()
true
> show collections
myColl
Dropping Collection Using Python
你可以通过调用 drop() 方法从当前目录中删除/丢弃一个集合。
Example
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)
Python MongoDB - Update
你可以使用 update() 方法或 save() 方法更新现有文档的内容。
更新方法修改现有的文档,而保存方法用新文档替换现有的文档。
Syntax
以下为 MangoDB 的 update() 和 save() 方法的语法 −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Or,
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
假设我们在一个数据库中创建了一个集合,并在其中插入了 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 的文档的城市值。
>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" }
同样,你可以使用 save() 方法通过使用相同的 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" }
Updating documents using python
与检索单个文档的 find_one() 方法类似,pymongo 的 update_one() 方法更新单个文档。
该方法接受一个查询,该查询指定要更新的文档和更新操作。
Example
以下 Python 示例更新集合中某个文档的位置值。
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)
Output
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() 方法更新满足指定条件的所有文档。
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
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)
Output
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() 方法限制结果中的文档数。此方法接受一个数字值,表示您希望在结果中显示的文档数。
Example
假设我们已经创建了一个集合,并在其中插入了 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" }
Limiting the Documents Using Python
为了将查询的结果限制为特定数量的文档,pymongo 提供了 limit() 方法。向此方法传递一个数字值,表示您希望在结果中显示的文档数。
Example
以下示例检索集合中的前三个文档。
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)