如何使用PyMongo从集合中动态选择字段?

时间:2019-04-24 11:37:45

标签: python python-3.x mongodb pymongo

我有一个MongoDb数据库。其中存储了几个集合。如何使用PyMongo在原始输入的基础上动态选择字段?

1 个答案:

答案 0 :(得分:0)

import pymongo
from pymongo import MongoClient
client = MongoClient()
client = MongoClient('localhost', 27017)

db = client['test-database']

import datetime
post = {"author": "Mike",
         "text": "My first blog post!",
         "tags": ["mongodb", "python", "pymongo"],
         "date": datetime.datetime.utcnow()}

posts = db.posts

post_id = posts.insert_one(post).inserted_id

for item in db.posts.find({},{ "_id": 0, "author": 1}):
    print(item)

从此https://www.w3schools.com/python/python_mongodb_find.asp,我们可以选择任何字段。

"_id"    : 0, # not select '_id' field
"author" : 1  #     select 'author' field