pymongo1.py

"""
功能:测试使用 pymongo 连接本地 mongodb。
"""
from pymongo import MongoClient
from pprint import pprint

# 1.
client = MongoClient()
# 确定数据库 test。
db = client.test
collection = db.posts

# 2.删除 posts 集合。
collection.drop()

# 3.插入一条文档。
post = {
    'author': 'Mike',
    'text': 'My first blog post!',
    'tags': ['mongodb', 'python', 'pymongo'],
    'likes': 10
}
collection.insert_one(post)

# 4.插入多条文档。
new_posts = [
    {
        "author": "Jimmy",
        "text": "another post",
        "tags": ["bulkinsert", "pymongo", "python"],
        "likes":20
    },
    {
        "author": "Emily",
        "text": "mongodb is fun",
        "tags": ["pymongo", "python"],
        "likes":30
    }
]
collection.insert_many(new_posts)

# 5.find_one()函数返回一条文档。
# print(collection.find_one())
doc = collection.find_one({}, {"_id": 0})
pprint(doc)

# 6.统计集合的文档数。
print(db.posts.estimated_document_count())  # 3


# # find(),返回多条文档。
# documents = db.posts.find({}, {"_id": 0})
# for post in documents:
#     pprint(post)
# print()
# # _id默认是显示的。
# documents = db.posts.find({'likes': {'$gte': 15}}, {
#     'author': 1, 'text': 1, 'likes': 1, '_id': 0})
# print("likes大于等于15的文档有:")
# for post in documents:
#     pprint(post)
#



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值