Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo find() vs mongodb find(), pymongo find() gives less data about document

I have a partner collection and I am using pymongo to retrieve the data
When I query the collection with MongoDB, I see the following result

db.partner.find({'unique_key': 'c89dbe313932008febde61cdd2a071a1d'},{})
{ "_id" : ObjectId("4eb463cb158acb554e8c9c11"), "unique_key" : "c89dbe313932008febde61cdd2a071a1d", "name" : "ABC", "primary_key" : 12 }  

But when I query via pymongo, here is what I do

for document in collection.find(find, criteria):
    print document  

where find = {'unique_key': 'c89dbe313932008febde61cdd2a071a1d'} and
      criteria = {}

Here is what I see in result:

{u'_id': ObjectId('4eb463cb158acb554e8c9c11')}  

and I don't get name and primary_key in result, am I missing something?

Thank you

like image 501
daydreamer Avatar asked Nov 14 '11 21:11

daydreamer


2 Answers

It seems that when you pass empty dictionary (your criteria variable) as the second parameter it means you want no fields returned (except _id that is always returned). The second parameter for find() defines the fields that you want. Try to set criteria=None or not pass criteria at all.

Link to the pymongo document for find().

like image 82
Lycha Avatar answered Oct 13 '22 11:10

Lycha


This is due to how the mongodb shell interprets {} as a field selector vs. how pymongo interprets an empty dictionary. In essence, the shell ignores the empty object as a field selector, whereas pymongo is interpreting it as "return nothing (except the default of _id)".

You don't need to specify a field selector when using pymongo or the mongodb shell (you can just leave it blank). Thus, this statement in the shell:

db.partner.find({'unique_key': 'c89dbe313932008febde61cdd2a071a1d'},{})

is equivalent to:

db.partner.find({'unique_key': 'c89dbe313932008febde61cdd2a071a1d'})

(this statement will work in both the shell and pymongo)

like image 40
dcrosta Avatar answered Oct 13 '22 11:10

dcrosta