简体   繁体   中英

Retrieve specific fields of all documents in mongodb collection

I have a mongodb collection user_col that looks like this;

[{
  '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. 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. I believe my code is quite close to getting it right.

I am using python 3.7, pymongo. I am also open to using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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