ssg
ssg

Reputation: 43

Pymongo only returning id field when empty object is passed

I have working with python and MongoDB. To connect to mongo I am using python module Pymongo. As I can see from documentation which is very abstract and small. It seems most of the things works as it works in normal MongoDB collection. But there is a strange part related to find query.

In Mongo Shell:

 db.my_collection.find({}, {})
 Results Array Fields:  { _id, field1, field1, field3 ..... etc} 
 //Notice:  Returning all Fields of each Document

In Python Shell:

 pymonogoMongoClient("localhost", 27017)['DB']['my_collection'].find({}, {})
 Results Array Fields:  {_id} 
 Notice  // Only Id is returning for all Docs

I understand that I get my desired results by not specifying empty {} in second argument of find but that is not what my code design allow. I am creating a kind of ORM for my Flask Application where I have to write generic Database function. And it is not allow.

Any help or get around to get all the Documents by passing an argument will be appreciated. Thanks in advance

Upvotes: 2

Views: 1168

Answers (1)

dnickless
dnickless

Reputation: 10918

According to the documentation here is why that happens:

projection (optional): a list of field names that should be returned in the result set or a dict specifying the fields to include or exclude. If projection is a list “_id” will always be returned. Use a dict to exclude fields from the result (e.g. projection={‘_id’: False}).

What you could do, though, is this:

if projection == {}:
    projection = None

pymonogoMongoClient("localhost", 27017)['DB']['my_collection'].find({}, projection)

Upvotes: 1

Related Questions