在這裏咱們來看一下Python3下MongoDB的存儲操做,在本節開始以前請確保你已經安裝好了MongoDB並啓動了其服務,另外安裝好了Python的PyMongo庫。html
MongoDB 數據庫安裝與介紹能夠查看以前的 MongoDB 教程。python
pip3 install pymongo
使用pymongo的第一步首先是鏈接Client來使用服務:數據庫
from pymongo import MongoClient Client = MongoClient()
在MongoDB中一個實例可以支持多個獨立的數據庫,你能夠用點取屬性的方式來獲取數據庫,或者經過字典的方式獲取:post
db = Client.test_database db = Client['test_database']
(注:'test'能夠換成你想要用的名字,好比"python_database")spa
Collection是存儲在MongoDB中的一組文件,同獲取database同樣,你能夠用點取屬性的方式或者字典的方法獲取:code
collection = db.test_collection collection = db['test_collection']
在MongoDB中,數據是以BSON的類型存儲的。見下面的post:htm
import datetime post = ['type':'BSON', 'date':datetime.datetime.utcnow()]
瞭解完MongoDB的數據格式後,你能夠經過如下的方式插入數據(其中.inserted_id將返回ObjectId對象):對象
document1 = {'x':1} document2 = {'x':2} posts = db.posts #你也能夠不這樣作,每次經過db.posts調用 post_1 = posts.insert_one(document1).inserted_id post_2 = posts.insert_one(document2).inserted_id
每一個插入的數據對應一個ObjectId,可直接查看:blog
>>>post_1 ObjectId(...) >>>post_2 ObjectId(...)
你還能夠用insert_many()插入多個文檔:教程
new_document = [{'x':3}, {'x':4}] result = posts.insert_many(new_document) >>>result.inserted_ids [ObjectId(...),ObjectId(...)]
>>>posts.find_one() ['x':'1']
但用find_one()的方法只能獲取一個數據,若是數據庫中存在多個數據時,它返回的是第一個的值。你也能夠經過ObjectId來請求數據,效果和上面是同樣的。若是你想打印出所有數據,能夠經過迭代的方式獲取:
>>>for data in posts.find(): >>> data >>>
{u'x':1, u'x':2, u'x':3, u'x':4}
你也能夠加入限制性因素來獲取特定的數據:
>>>for post in posts.find({'x':1}): >>> post >>> {u'x':1}
查找條件中也能夠用正則匹配來匹配calue。
在pymongo中能夠用update_one()來更新數據:
>>>posts.update_one({'x':4},{'$set':{'x':3}})
其中傳入的第一個參數是你想要更新的數據,第二個是你想要更新的最新數據。其中$set部分是必要元素,若是沒有會報出錯誤。除了$set外還有不少其它的好比$inc,對應着不一樣的功能,在此先不贅述。
上面只是更新匹配到的第一個數據,一樣地,也能夠用update_many()一次更新多個值。
同上,能夠用delete_one()和delete_many()方法來刪除數據,括號中是篩選條件:
>>>posts.delete_one({'x':3}) >>>posts.delete_one({'x':2})
若是想知道collection中有多少文檔,能夠用.count()請求來獲取符合條件的文檔。
>>>posts.count() 4 >>>posts.find({'x':1}) 1
完!!!