""" 功能:测试使用 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) #
pymongo1.py
于 2019-05-24 11:11:56 首次发布