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'}
廣告