|
MongoDB是由C++語言編寫的非關(guān)系型數(shù)據(jù)庫,是一個(gè)基于分布式文件存儲(chǔ)的開源數(shù)據(jù)庫系統(tǒng),其內(nèi)容存儲(chǔ)形式類似JSON對象,它的字段值可以包含其他文檔、數(shù)組及文檔數(shù)組,非常靈活。在這一節(jié)中,我們就來看看Python 3下MongoDB的存儲(chǔ)操作。 1. 準(zhǔn)備工作在開始之前,請確保已經(jīng)安裝好了MongoDB并啟動(dòng)了其服務(wù),并且安裝好了Python的PyMongo庫。 2. 連接MongoDB連接MongoDB時(shí),我們需要使用PyMongo庫里面的 import pymongo client = pymongo.MongoClient(host='localhost', port=27017) 這樣就可以創(chuàng)建MongoDB的連接對象了。 另外, client = MongoClient('mongodb://localhost:27017/')這也可以達(dá)到同樣的連接效果。 3. 指定數(shù)據(jù)庫MongoDB中可以建立多個(gè)數(shù)據(jù)庫,接下來我們需要指定操作哪個(gè)數(shù)據(jù)庫。這里我們以test數(shù)據(jù)庫為例來說明,下一步需要在程序中指定要使用的數(shù)據(jù)庫: db = client.test 這里調(diào)用 db = client['test'] 這兩種方式是等價(jià)的。 4. 指定集合MongoDB的每個(gè)數(shù)據(jù)庫又包含許多集合(collection),它們類似于關(guān)系型數(shù)據(jù)庫中的表。 下一步需要指定要操作的集合,這里指定一個(gè)集合名稱為students。與指定數(shù)據(jù)庫類似,指定集合也有兩種方式: collection = db.students collection = db['students'] 這樣我們便聲明了一個(gè) 5. 插入數(shù)據(jù)接下來,便可以插入數(shù)據(jù)了。對于students這個(gè)集合,新建一條學(xué)生數(shù)據(jù),這條數(shù)據(jù)以字典形式表示: student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}這里指定了學(xué)生的學(xué)號(hào)、姓名、年齡和性別。接下來,直接調(diào)用 result = collection.insert(student) print(result) 在MongoDB中,每條數(shù)據(jù)其實(shí)都有一個(gè) 運(yùn)行結(jié)果如下: 5932a68615c2606814c91f3d 當(dāng)然,我們也可以同時(shí)插入多條數(shù)據(jù),只需要以列表形式傳遞即可,示例如下: student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
result = collection.insert([student1, student2])
print(result)返回結(jié)果是對應(yīng)的 [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]實(shí)際上,在PyMongo 3.x版本中,官方已經(jīng)不推薦使用 student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)運(yùn)行結(jié)果如下: <pymongo.results.InsertOneResult object at 0x10d68b558> 5932ab0f15c2606f0c1cf6c5 與 對于 student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)運(yùn)行結(jié)果如下: <pymongo.results.InsertManyResult object at 0x101dea558>
[ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]該方法返回的類型是 6. 查詢插入數(shù)據(jù)后,我們可以利用 result = collection.find_one({'name': 'Mike'})
print(type(result))
print(result)這里我們查詢 <class 'dict'>
{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}可以發(fā)現(xiàn),它多了 此外,我們也可以根據(jù) from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)其查詢結(jié)果依然是字典類型,具體如下: {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}當(dāng)然,如果查詢結(jié)果不存在,則會(huì)返回 對于多條數(shù)據(jù)的查詢,我們可以使用 results = collection.find({'age': 20})
print(results)
for result in results:
print(result)運(yùn)行結(jié)果如下: <pymongo.cursor.Cursor object at 0x1032d5128>
{'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'}返回結(jié)果是 如果要查詢年齡大于20的數(shù)據(jù),則寫法如下: results = collection.find({'age': {'$gt': 20}})這里查詢的條件鍵值已經(jīng)不是單純的數(shù)字了,而是一個(gè)字典,其鍵名為比較符號(hào) 這里將比較符號(hào)歸納為下表。
另外,還可以進(jìn)行正則匹配查詢。例如,查詢名字以M開頭的學(xué)生數(shù)據(jù),示例如下: results = collection.find({'name': {'$regex': '^M.*'}})這里使用 這里將一些功能符號(hào)再歸類為下表。
關(guān)于這些操作的更詳細(xì)用法,可以在MongoDB官方文檔找到: https://docs./manual/reference/operator/query/。 7. 計(jì)數(shù)要統(tǒng)計(jì)查詢結(jié)果有多少條數(shù)據(jù),可以調(diào)用 count = collection.find().count() print(count) 或者統(tǒng)計(jì)符合某個(gè)條件的數(shù)據(jù): count = collection.find({'age': 20}).count()
print(count)運(yùn)行結(jié)果是一個(gè)數(shù)值,即符合條件的數(shù)據(jù)條數(shù)。 8. 排序排序時(shí),直接調(diào)用 results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])運(yùn)行結(jié)果如下: ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike'] 這里我們調(diào)用 9. 偏移在某些情況下,我們可能想只取某幾個(gè)元素,這時(shí)可以利用 results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])運(yùn)行結(jié)果如下: ['Kevin', 'Mark', 'Mike'] 另外,還可以用 results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])運(yùn)行結(jié)果如下: ['Kevin', 'Mark'] 如果不使用 值得注意的是,在數(shù)據(jù)庫數(shù)量非常龐大的時(shí)候,如千萬、億級別,最好不要使用大的偏移量來查詢數(shù)據(jù),因?yàn)檫@樣很可能導(dǎo)致內(nèi)存溢出。此時(shí)可以使用類似如下操作來查詢: from bson.objectid import ObjectId
collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})這時(shí)需要記錄好上次查詢的 10. 更新對于數(shù)據(jù)更新,我們可以使用 condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)這里我們要更新 運(yùn)行結(jié)果如下: {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}返回結(jié)果是字典形式, 另外,我們也可以使用 result = collection.update(condition, {'$set': student})這樣可以只更新 另外, condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)這里調(diào)用了 運(yùn)行結(jié)果如下: <pymongo.results.UpdateResult object at 0x10d17b678> 1 0 我們再看一個(gè)例子: condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)這里指定查詢條件為年齡大于20,然后更新條件為 運(yùn)行結(jié)果如下: <pymongo.results.UpdateResult object at 0x10b8874c8> 1 1 可以看到匹配條數(shù)為1條,影響條數(shù)也為1條。 如果調(diào)用 condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)這時(shí)匹配條數(shù)就不再為1條了,運(yùn)行結(jié)果如下: <pymongo.results.UpdateResult object at 0x10c6384c8> 3 3 可以看到,這時(shí)所有匹配到的數(shù)據(jù)都會(huì)被更新。 11. 刪除刪除操作比較簡單,直接調(diào)用 result = collection.remove({'name': 'Kevin'})
print(result)運(yùn)行結(jié)果如下: {'ok': 1, 'n': 1}另外,這里依然存在兩個(gè)新的推薦方法—— result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)運(yùn)行結(jié)果如下: <pymongo.results.DeleteResult object at 0x10e6ba4c8> 1 4
12. 其他操作另外,PyMongo還提供了一些組合方法,如 另外,還可以對索引進(jìn)行操作,相關(guān)方法有 關(guān)于PyMongo的詳細(xì)用法,可以參見官方文檔:http://api./python/current/api/pymongo/collection.html。 另外,還有對數(shù)據(jù)庫和集合本身等的一些操作,這里不再一一講解,可以參見官方文檔:http://api./python/current/api/pymongo/。 本節(jié)講解了使用PyMongo操作MongoDB進(jìn)行數(shù)據(jù)增刪改查的方法。 |
|
|