1 | pip install pymongo |
---|
12345 | from pymongo import MongoClient# 以下为三种建立连接的方式#client = MongoClient()#client = MongoClient('localhost', 27017)#client = MongoClient('mongodb://localhost:27017/') |
---|
123 | # 以下是两种获取数据库的方式db = client.pythondbdb = client['python-db'] |
---|
123 | # 以下是两种获取集合的方式collection = db.python_collectioncollection = db['python-collection'] |
---|
上述任何命令都没有在MongoDB服务器上实际执行任何操作。当第一个文档插入集合时才创建集合和数据库。
12345678910111213141516171819 | #!/usr/bin/python3#coding=utf-8import datetimefrom pymongo import MongoClientclient = MongoClient()db = client.pythondbposts = db.postspost = {"author": "Maxsu", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()}posts.insert(post)# 批量插入,参数为listposts.insert_many(new_posts) |
---|
123456789101112131415161718192021 | #!/usr/bin/python3#coding=utf-8import datetimeimport pprintfrom pymongo import MongoClientclient = MongoClient()db = client.pythondbposts = db.posts# 查找单个文档print(posts.find_one())# 查找多个文档for post in posts.find(): print(post)# 计数统计print(posts.count())print(posts.find({"author": "Maxsu"}).count()) |
---|
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有