Python – Getting a dictionary inside a list by key in mongoDB (mongoengine)

mongodbmongoenginepython

I'm using mongoDB (mongoHQ) in my Flask app (mongoengine).
I have a Document that looks like this:

{items: [{id: 1}, {id: 2}, {id: 3}]}

Is there a way to to reach, for example, the dict with id: 1 in a single query?

Currently I'm looping through the items list with a next() statement and I was hoping for a wiser solution. Thanks

Best Answer

I'm not familiar with MongoEngine, but the $ projection operator can filter an array to show only the matched element. In the Mongo shell:

> db.foo.insert({"items": [{"id": 1}, {"id": 2}, {"id": 3}]})
> db.foo.find({'items.id': 1}, {'items.$': true})
{ "_id" : ObjectId("51ce29b68b178484ff2a01ed"), "items" : [  {  "id" : 1 } ] }

More info: http://docs.mongodb.org/manual/reference/projection/positional/

It seems in MongoEngine you do:

Foo.objects(__raw__={'items.id': 1}).only('items.$')

More: http://mongoengine-odm.readthedocs.org/en/latest/guide/querying.html#raw-queries