1.連接mongodb
######### 方法一 ########## import pymongo # MongoClient()返回一個mongodb的連接對象client client = pymongo.MongoClient(host="localhost",port=27017) ######### 方法二 ########## import pymongo # MongoClient的第一個參數host還可以直接傳MongoDB的連接字符串,以mongodb開頭 client = pymongo.MongoClient(host="mongodb://127.0.0.1:27017/")
2.指定數據庫
###### 方法一 ###### # 指定test數據庫 db = client.test ###### 方法二 ###### # 指定test數據庫(調用client的test屬性即可返回test數據庫) db = client["test"]
3.指定集合
###### 方法一 ###### # 指定student集合 collection = db.student ###### 方法二 ###### # 指定student集合 collection = db["student"]
4.插入數據
- db.collection.insert()
可以插入一條數據(dict),也可以插入多條數據(list),返回‘_id’或‘_id’的集合
###### 插入一條數據 ###### student = { 'name': 'Jordan', 'age': 18, 'gender': 'man' } result = db.collection.insert(student) # insert()返回執行后文檔的主鍵'_id'的值 print(result) # 5932a68615c2606814c91f3d ###### 插入多條數據 ###### student1 = { 'name': 'Jordan', 'age': 10, 'gender': 'man' } student2 = { 'name': 'Mike', 'age': 11, 'gender': 'man' } result = collection.insert([student1,student2]) # insert()返回執行后文檔的主鍵'_id'的集合 print(result) #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
pymongo 3.x版本中,insert()方法官方已不推薦使用,推薦使用insert_one()和insert_many()將插入單條和多條記錄分開。
- db.collection.insert_one()
用於插入單條記錄,返回的是InsertOneResult對象
student = { 'name': 'Jordan', 'age': 18, 'gender': 'man' } result = collection.insert_one(student) # insert_one()返回的是InsertOneResult對象,我們可以調用其inserted_id屬性獲取_id。 print(result) # <pymongo.results.InsertOneResult object at 0x10d68b558> print(result.inserted_id) # 5932ab0f15c2606f0c1cf6c5
- db.collection.insert_many()
用於插入多條記錄,返回的是InsertManyResult對象
student1 = { 'name': 'Jordan', 'age': 10, 'gender': 'man' } student2 = { 'name': 'Mike', 'age': 11, 'gender': 'man' } result = collection.insert_many([student1, student2]) # insert_many()方法返回的類型是InsertManyResult,調用inserted_ids屬性可以獲取插入數據的_id列表 print(result) # <pymongo.results.InsertManyResult object at 0x101dea558> print(result.inserted_ids) # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]
5.查詢數據:find_one()、find()
- db.collection.find_one()
查詢返回單個結果(dict或者None)
result = db.collection.find_one({"name": "Mike"}) print(result) #{'_id': ObjectId('5932a80115c2606a59e8a049'),'name': 'Mike', 'age': 21, 'gende' :'man'} db.collection.find() 查詢返回多個結果(cursor類型,可迭代)。 results = collection.find({"age":18}) print(results) # <pymongo.cursor.Cursor object at 0x1032d5128> for result in results: print(result) #
-
查詢條件

- 多條件查詢
$and
$or
# and查詢 db.collection.find({ $and : [ { "age" : {$gt : 10 }} , { "gender" : "man" } ] }) #or查詢 db.collection.find({ $or : [ {"age" : {$gt : 10 }}, { "gender" : "man"} ] }) #and查詢 和 or查詢 db.inventory.find( { $and : [ { $or : [ { price : 0.99 }, { price : 1.99 } ] }, { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } ] } )
- count()
計數,對查詢結果進行個數統計
count = collection.find().count() print(count)
- 排序
sort()
調用sort方法,傳入要排序的字段and升降序標志即可
#單列升序排列 results = db.collection.find().sort('name', pymongo.ASCENDING) # 升序(默認) print([result['name'] for result in results]) # 單列降序排列 results = db.collection.find().sort("name",pymongo.DESCENDING) #降序 print([result['name'] for result in results]) #多列排序 results = db.collection.find().sort([ ("name", pymongo.ASCENDING),("age", pymongo.DESCENDING) ])
- 偏移
skip()
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) print([result['name'] for result in results])
注意:在數據量非常龐大時(千萬、億級別),最好不要用skip()來查詢數據,可能導致內存溢出。可以使用
find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})
這樣的方法來查詢。
- 限制
limit()
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) print([result['name'] for result in results])
6.更新數據
- db.collection.update()
修改單條或者多條文檔,已不推薦此用法
result = collection.update( {"age": {"$lt" : 15}} , {"$set" : {"gender" : "woman"}} ) print(result) # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
- db.collection.update_one()
修改單條文檔,返回結果是UpdateResult類型
針對UpdateResult類型數據,可以調用matched_count和modified_count屬性分別獲取匹配的條數和影響的條數
result = db.collection.update_one( {"name" : "Mike"} , { "$inc" : {"age" : 5}, "$set": {"gender": "male"} } ) print(result) # <pymongo.results.UpdateResult object at 0x10d17b678> print(result.matched_count, result.modified_count) # 1 1
- db.collection.update_many()
修改多條文檔,返回結果是UpdateResult類型
result = db.collection.update_many( {"name" : "Mike"} , {"$inc" : {"age" : 5}} ) print(result) # <pymongo.results.UpdateResult object at 0x10c6384c8> print(result.matched_count, result.modified_count) # 3 3
7.刪除數據
- db.collection.remove()
刪除指定條件的所有數據
result = db.collection.remove({"age" : {"$gte" : 10}}) print(result) # {'ok': 3, 'n': 3}
- db.collection.delete_one()
刪除第一條符合條件的數據,返回DeleteResult類型數據
result = collection.delete_one({'name': 'Kevin'}) print(result) # <pymongo.results.DeleteResult object at 0x10e6ba4c8> print(result.deleted_count) # 1
- db.collection.delete_many()
刪除所有符合條件的數據,返回DeleteResult類型數據
result = collection.delete_many({'name': 'Kevin'}) print(result) # <pymongo.results.DeleteResult object at 0x55e6be5f1> print(result.deleted_count) # 4
另外,pymongo還提供了更多方法,如find_one_and_delete()
find_one_and_replace()
find_one_and_update()
,當然,還有操作索引的方法:create_index()
create_indexes()
drop_index()
等。
import pymongo client = pymongo.MongoClient(host="127.0.0.1", port="27017") db = client["test"] coll = db["myindex"] # 在后台創建唯一索引 coll.create_index([(x,1)], unique = True, background = True,name = "x_1") # 查看集合coll的所有索引信息 result = coll.index_information() print(result) # 在后台創建復合索引 db.myindex.create_index([("x", 1), ("y", 1)]) # 刪除索引 coll.drop_index([("x", 1)]) # coll.drop_index("x_1")
詳細用法可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html
另外還有對數據庫、集合本身以及其他的一些操作,在這不再一一講解,可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/