pymongo 入门

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 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,002评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,076评论 25 708
  • “你可曾听说过月老?” “那个掌管世间姻缘的神仙?” “不错。” "我听说,如果月老用红线系住有情人,这对有情人就...
    泥藏风阅读 315评论 0 2
  • 护肤已经成为 我们每天生活的日常 但我们每天都在坚持的 护肤习惯是对的吗 护肤恶习一 把紧肤水直接倒在手上,以为用...
    希颂美聊阅读 342评论 0 1
  • 如果有人一直关注我,会发现在我写完《初来乍到》后的这一个月里,我也曾公开了几篇文章,但一天之内又消失了。最后的结果...
    少为同学阅读 1,171评论 26 30

友情链接更多精彩内容