python操作mongo

在python中,連接並操作mongo主要使用了pymongo庫。


mongo連接

先安裝mongo,並創建一個庫:mytest,collection爲Person,插入一條記錄:_id:1。連接並查詢:

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client.mytest
collection = db.Person
result = collection.find_one()
print result

輸出結果如下:

{u'_id':1.0}

首先,要連接上mongoDB,通過pymongo庫裏的MongoClient來實現。傳入host和port兩個參數,或者直接傳入一個連接字符串也行,如下所示:

client = MongoClient('mongodb://localhost:27017/')

然後,獲取到db和collection。client.mytest和client[‘mytest’]這兩種方式是一樣的效果。同樣地,指定操作集合時,db.Person和db[‘Person’]也是一樣的。

當collection中存在數據時,可通過collection的find()或find_one()方法來查詢結果,其中find_one()查詢得到的是單個結果,而find()則返回一個生成器對象。

CRUD操作

insert

現在往collection中插入數據。

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client.mytest
collection = db.Person
person = { "name": "Mike"}
collection.insert(person)
cur = collection.find()
for c in cur:    
	print c

輸出結果如下:

{u'_id':1.0}
{u'_id': ObjectId('5cd8e716fcc8c12d8ee405ce'), u'name': u'Mike'}

第一條數據是從外面插入的,指定了_id爲1。此處插入name爲Mike的這條數據,由系統自動生成了ObjectId。

在Mongo3.x版本中官方已經不推薦使用insert()方法,而是替換成了insert_one()和insert_many(),用於插入單條記錄和多條記錄。
insert方法返回的結果是標識id(_id)列表,而insert_one方法返回的是一個InsertOneResult對象,通過inserted_id屬性獲取_id。

find

find()方法返回一個生成器對象,需要進行遍歷才能得到對應的dict對象。而find_one()方法直接返回的就是一個dict對象。

import pymongo

client = pymongo.Mongo
Client(host='localhost', port=27017)
db = client.mytest
collection = db.Person
curson = collection.find({"name": "Mike"})
print("curson type is %s" % type(curson))
for c in curson:    
	print("c type is %s " % type(c))    
	print c

結果如下:

    curson type is <class 'pymongo.cursor.Cursor'>
    c type is <type 'dict'> 
    {u'_id': ObjectId('5cd8e716fcc8c12d8ee405ce'), u'name': u'Mike'}

除了字符串精確匹配查詢之外,對於整形,支持以下操作:

符號 含義 示例
$lt,$gt 小於, 大於 {‘age’: {’$lt’: 20}}
$lte, $gte 小於等於,大於等於 {‘age’: {’$lte’: 20}}
$ne 不等於 {‘age’: {’$ne’: 20}}
$in 在範圍內 {‘age’: {’$in’: [20, 23]}}
$nin 不在範圍內 {‘age’: {’$nin’: [20, 23]}}

還有其他一些高級的用法如下所示:

符號 含義 示例 說明
$regex 正則匹配 {‘name’: {’$regex’: ‘^M.*’}}
$exists 屬性是否存在 {‘name’: {’$exists’: True}}
$type 類型判斷 {‘age’: {’$type’: ‘int’}} age的類型爲int
$mod 數字模操作 {‘age’: {’$mod’: [5, 0]}} 年齡模5餘0
$text 文本查詢 {’$text’:{’$search’: ‘Mike’}} text類型的屬性中包含Mike字符串
$where 高級條件查詢 {’$where’: ‘obj.fans_count == obj.follows_count’} 自身粉絲數等於關注數

count,sort,skip,limit

計數直接調用count函數:
count = collection.find().count()count = collection.find({'name':'Mike'}).count()
排序直接調用sort函數:
results = collection.find().sort('name', pymongo.ASCENDING),降序爲pymongo.DESCENDING
偏移直接調用skip函數:

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)

限制查詢結果數直接調用limit函數:

results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)

update

使用update()進行數據更新:

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print result

運行結果如下:

{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

返回字典形式結果, ok表示執行成功,nModified表示影響條數。

也可以使用$set操作符對數據進行更新,如下所示:

result = collection.update(condition, {'$set': student})

是否使用$set的區別在於:
不使用$set時,會使用當前更新的字典對象替換原對象,新對象中不含而舊對象中存在的字段會消失。
使用$set時,則只更新新對象中存在的字段,舊對象的其他字段保持不變。

實際上,update也是官方不推薦使用的方法,推薦的是update_oneupdate_many,它們的第二個參數必須使用$set作爲字典的鍵名,不允許直接傳入修改後的新字典對象。

result = collection.update_one({"name": "Mike"}, {"$set": {"name": "Tom"}})
print result, result.matched_count, result.modified_count
cur = collection.find()
for r in cur:    
	print r

update_one和update_many方法返回的結果是一個UpdateResult,其中matched_count屬性和modified_count屬性分別表示匹配的數據條數和影響的數據條數。

update_many會更新所有符合條件的數據。

批量更新

update_many可以更新符合條件的多條數據,這是一種意義上的批量更新。還有另外一種批量更新,指的是將多次更新操作一起執行,如下所示:

op1 = pymongo.UpdateOne({"name": "Mike"}, {"$set": {"name": "Tom"}})
op2 = pymongo.UpdateOne({"name": "Jack"}, {"$set": {"name":"Hanse"}})
update_operations.append(op1)
update_operations.append(op2)
collection.bulk_write(ops)

delete

刪除操作通過remove函數來進行,在參數中指定刪除條件:

result = collection.remove({"name": "Mike"})

remove返回結果是一個dict對象:

{'ok': 1, 'n': 1}

表示執行成功,刪除條數爲1。

同樣地,官方推薦方法爲delete_one()和delete_many(),返回結果是DeleteResult對象,其中的deleted_count屬性爲刪除的數據條數。

組合操作

其他還有一些組合操作,如find_one_and_delete(),finde_one_and_replace,find_one_and_update。

參考

[1]https://juejin.im/post/5addbd0e518825671f2f62ee
[2]https://docs.mongodb.com/manual/reference/operator/query/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章