環境描述
- Python 3.6.3
- pip 9.0.1
- Windows 10
安裝
pip install pymongo
與數據庫建立連接
from pymongo import MongoClient # 導入包
user = "root" # 連接的用戶名
password = "123456" # 密碼
host = "localhost" # 連接的數據庫主機
uri = "mongodb://{user}:{password}@{host}".format(user=user,password=password,host=host) # 設置連接的uri
client = MongoClient(uri) # 建立連接
獲取數據庫
db = client.db_name # 訪問屬性的方式
db = client["db_name"] # 採用字典的方式
獲取集合
collection = db.collection_name # 範文屬性的方式
collection = db["collection_name"] # 字典方式獲取
插入文檔
插入一個文檔
client = MongoClient(uri)
db = client.newspaper
test = db.test
document = { # 要插入的文檔
"name":789
}
# insert_one()一次插入一個文檔
doc_id = test.insert_one(document).inserted_id # 返回文檔_id
print(doc_id)
批量插入
client = MongoClient(uri)
db = client.newspaper
test = db.test
documents = [{"name":789},{"name":456}]# 要插入的文檔
# insert_many() 批量插入文檔數組
result = test.insert_many(documents)
print(result.inserted_ids)
查詢文檔
單文檔查詢
result1 = test.find_one() # 查找集合中的第一個文檔
result2 = test.find_one({"name":456}) # 查找符合條件的文檔的第一個
print(result1)
print(result2)
多文檔查詢
find()返回一個Cursor實例,它允許遍歷所有匹配的文檔
results = test.find() # 查找集合中所有的文檔
print(results.count()) # 返回查詢結果的條數
for res in results: #遍歷
print(res)
results = test.find({"name":789}) # 查找所有匹配的文檔
print(results.count()) # 返回查詢結果的條數
for res in results: # 遍歷
print(res)
find()中的查詢條件可以是MongoDB中的其他條件,包括範圍查詢和and,or操作
建立唯一索引
添加索引可以幫助加速某些查詢,並且還可以添加額外的功能來查詢和存儲文檔。在這個例子中,將演示如何在一個鍵上創建一個唯一的索引,該索引將拒絕已經存在值的文檔插入。
result = db.test.create_index([('name', pymongo.ASCENDING)], unique=True)
sorted(list(db.test.index_information()))
現在有兩個索引:一個是MongoDB自動創建的在_id索引,另一個是剛剛創建在name上的索引。