Pymongo 使用流程
使用语言: python3.6
环境 : 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.获取 一个 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 插入单个数据
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. 获取单个数据
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.条件查询单个数据
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 根据 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 查询多个数据
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 多个数据条件查询
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 计数
posts.count()
3
13 条件计数
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