Hemant
Hemant

Reputation: 649

Difference between the results from _get_collection().find and objects() in pymongo

I am using pymongo to query mongodb. I have collection named alph_var and a document in this collection looks like this: {'a':'1','c':None,'d':'1sfa','e':None}

If I am doing alph_var._get_collection().find({'a':'1'}), I am getting following result:

{'_id':ObjectId('1242as223'),'a':'1','d':'1sfa'}

and when I am doing alph_var.objects(a='1')[0]._data, I am getting following result:

{'id':ObjectId('1242as223'), 'a':'1','c':None,'d':'1sfa','e':None}

I am completely new to pymongo, any idea why this is happening?

Upvotes: 0

Views: 1128

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

I see you're using MongoEngine, a wrapper ("Object Document Mapper") around PyMongo. When you call _get_collection and get a handle to the underlying PyMongo Collection instance, and query it, you get a raw representation of the BSON documents in MongoDB with no further processing. Evidently this particular document only has fields "_id", "a", and "d". It does not contain fields "c" and "e" at all. (MongoDB documents can include or omit any field but "_id".)

When you use MongoEngine, however, it enforces a schema on your documents. I think you've defined fields "c" and "e" in your MongoEngine schema. So when MongoEngine retrieves the document, it sees that the document lacks "c" and "e", so it sets them to None in its internal "_data" dict.

Upvotes: 2

Related Questions