pymongo 入門(mén)

Pymongo 使用流程

使用語(yǔ)言: python3.6
環(huán)境 : Windows 10,Docker(Mongodb)

0 安裝##

pip install pymongo

1.鏈接

import pymongo
from pymongo import MongoClient
client=MongoClient("localhost",27017)

2.獲取 databases 鏈接

db = client['test-database']

3.獲取 一個(gè) Collection

collection = db['test-collection']

4.Documents

import datetime
post = {"author": "Mike",
       "text": "My first blog post!",
       "tags": ["mongodb", "python", "pymongo"],
       "date": datetime.datetime.utcnow()}

5 插入單個(gè)數(shù)據(jù)

posts = db.posts
post_id = posts.insert_one(post).inserted_id
print(post_id)
59be0170bf94d71efc40a7ce

獲取 collections 名稱(chēng)

db.collection_names(include_system_collections=False)
['posts']

6. 獲取單個(gè)數(shù)據(jù)

import pprint
pprint.pprint(posts.find_one())
{'_id': ObjectId('59be0170bf94d71efc40a7ce'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 9, 17, 5, 0, 31, 418000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

7.條件查詢(xún)單個(gè)數(shù)據(jù)

 pprint.pprint(posts.find_one({"author": "Mike"}))
{'_id': ObjectId('59be0170bf94d71efc40a7ce'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 9, 17, 5, 0, 31, 418000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
posts.find_one({"author": "Eliot"})

8 根據(jù) ID 查詢(xún)

print(post_id)

59be0170bf94d71efc40a7ce
pprint.pprint(posts.find_one({"_id": post_id}))
{'_id': ObjectId('59be0170bf94d71efc40a7ce'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 9, 17, 5, 0, 31, 418000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

id 不是字符串

post_id_as_str = str(post_id)
posts.find_one({"_id": post_id_as_str})
from bson.objectid import ObjectId
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})
print(get(post_id))
None
post_id
ObjectId('59be0170bf94d71efc40a7ce')

9 批量插入

new_posts = [{"author": "Mike",
               "text": "Another post!",
               "tags": ["bulk", "insert"],
               "date": datetime.datetime(2009, 11, 12, 11, 14)},
              {"author": "Eliot",
               "title": "MongoDB is fun",
              "text": "and pretty easy too!",
               "date": datetime.datetime(2009, 11, 10, 10, 45)}]
result = posts.insert_many(new_posts)
result.inserted_ids
[ObjectId('59be0175bf94d71efc40a7cf'), ObjectId('59be0175bf94d71efc40a7d0')]

10 查詢(xún)多個(gè)數(shù)據(jù)

for post in posts.find():
    pprint.pprint(post)
{'_id': ObjectId('59be0170bf94d71efc40a7ce'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 9, 17, 5, 0, 31, 418000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
{'_id': ObjectId('59be0175bf94d71efc40a7cf'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}
{'_id': ObjectId('59be0175bf94d71efc40a7d0'),
 'author': 'Eliot',
 'date': datetime.datetime(2009, 11, 10, 10, 45),
 'text': 'and pretty easy too!',
 'title': 'MongoDB is fun'}

11 多個(gè)數(shù)據(jù)條件查詢(xún)

for post in posts.find({"author": "Mike"}):
    pprint.pprint(post)
{'_id': ObjectId('59be0170bf94d71efc40a7ce'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 9, 17, 5, 0, 31, 418000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
{'_id': ObjectId('59be0175bf94d71efc40a7cf'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}

12 計(jì)數(shù)

posts.count()
3

13 條件計(jì)數(shù)

posts.find({"author": "Mike"}).count()
2

14 范圍查詢(xún)

d = datetime.datetime(2015, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
    pprint.pprint(post)
{'_id': ObjectId('59be0175bf94d71efc40a7d0'),
 'author': 'Eliot',
 'date': datetime.datetime(2009, 11, 10, 10, 45),
 'text': 'and pretty easy too!',
 'title': 'MongoDB is fun'}
{'_id': ObjectId('59be0175bf94d71efc40a7cf'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}

15 index

result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],
                                  unique=True)
sorted(list(db.profiles.index_information()))
['_id_', 'user_id_1']
user_profiles = [
     {'user_id': 211, 'name': 'Luke'},
     {'user_id': 212, 'name': 'Ziltoid'}]
result = db.profiles.insert_many(user_profiles)
new_profile = {'user_id': 213, 'name': 'Drew'}
duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
 result = db.profiles.insert_one(new_profile)  # This is fine.
result = db.profiles.insert_one(duplicate_profile)
---------------------------------------------------------------------------

DuplicateKeyError                         Traceback (most recent call last)

<ipython-input-75-5816b1ed923c> in <module>()
----> 1 result = db.profiles.insert_one(duplicate_profile)


d:\app\XXXX\anaconda3\envs\pynt\lib\site-packages\pymongo\collection.py in insert_one(self, document, bypass_document_validation)
    668             return InsertOneResult(
    669                 self._insert(sock_info, document,
--> 670                              bypass_doc_val=bypass_document_validation),
    671                 self.write_concern.acknowledged)
    672 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評(píng)論 18 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,242評(píng)論 25 708
  • “你可曾聽(tīng)說(shuō)過(guò)月老?” “那個(gè)掌管世間姻緣的神仙?” “不錯(cuò)?!?"我聽(tīng)說(shuō),如果月老用紅線(xiàn)系住有情人,這對(duì)有情人就...
    泥藏風(fēng)閱讀 255評(píng)論 0 2
  • 護(hù)膚已經(jīng)成為 我們每天生活的日常 但我們每天都在堅(jiān)持的 護(hù)膚習(xí)慣是對(duì)的嗎 護(hù)膚惡習(xí)一 把緊膚水直接倒在手上,以為用...
    希頌美聊閱讀 298評(píng)論 0 1
  • 如果有人一直關(guān)注我,會(huì)發(fā)現(xiàn)在我寫(xiě)完《初來(lái)乍到》后的這一個(gè)月里,我也曾公開(kāi)了幾篇文章,但一天之內(nèi)又消失了。最后的結(jié)果...
    少為同學(xué)閱讀 1,065評(píng)論 26 30