简体   繁体   English

检索 mongodb 集合中所有文档的特定字段

[英]Retrieve specific fields of all documents in mongodb collection

I have a mongodb collection user_col that looks like this;我有一个看起来像这样的 mongodb 集合user_col

[{
  'Code': '557921',
  'Serial': 0,
  'UserName': 'morbidMacaw674005',
  '_id': ObjectId('5ee328c32cd209a5f60b56f1')},
 {
  'Code': '127142',
  'Serial': 1,
  'UserName': 'jumpyChough940073',
  '_id': ObjectId('5ee328c32cd209a5f60b56f2')},
 {
  'Code': '739173',
  'Serial': 2,
  'UserName': 'jumpyPretzels824773',
  '_id': ObjectId('5ee328c32cd209a5f60b56f3')},
]

I want to retrieve specific fields of all documents in a mongodb collection into a list of dictionaries.我想将 mongodb 集合中所有文档的特定字段检索到字典列表中。 Here is my code;这是我的代码;

list(user_col.find({"UserName": 1, "Code": 1}))

However, it returns nothing.但是,它什么也不返回。 What is wrong with my code?我的代码有什么问题?

If I run list(user_col.find({})) , all the documents are retrieved.如果我运行list(user_col.find({})) ,将检索所有文档。 I believe my code is quite close to getting it right.我相信我的代码非常接近正确。

I am using python 3.7, pymongo.我正在使用 python 3.7,pymongo。 I am also open to using mongoengine.我也愿意使用 mongoengine。

I will answer my own question.我会回答我自己的问题。

list(user_col.find({}, {"UserName": 1, "Code": 1}))

The first parameter {} was missing in the code in the question.问题的代码中缺少第一个参数{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM