Pymongo 使用流程
使用語言: 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 名稱
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.條件查詢單個(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 查詢
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 查詢多個(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ù)條件查詢
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 范圍查詢
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