4

I have a collection with documents like this:

{ 
    key : "bla"
    list : [
       {id:1}, 
       {id:2}
    ]
}

How do I get this object: {id:1} ?

I tried a query like this: db.myCollection.find({"key":"bla", "list.id":1})

it finds the entry, but returns the complete document instead of only {id:1}

User
  • 31,811
  • 40
  • 131
  • 232
  • possible duplicate of [MongoDB extract only the selected item in array](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array) – JohnnyHK Aug 25 '13 at 22:05

1 Answers1

4

The $ operator is what you're looking for:

db.test.insert({key: "blah",list :[{id:1},{id:2}]})

db.test.find({'list.id' : 1},{'list.$': 1 })
#Returns:
#{ "_id" : ObjectId("521a78b342abf388fbaacf91"), "list" : [ { "id" : 1 } ] }

db.test.find({'list.id' : 2},{'list.$': 1 })
#Returns:
#{ "_id" : ObjectId("521a78b342abf388fbaacf91"), "list" : [ { "id" : 2 } ] }

If you don't need the _id of the document, you can exclude that too:

db.test.find({'list.id' : 2},{'list.$': 1 , _id: 0})
#Returns:
#{ "list" : [ { "id" : 2 } ] }

For more information, have a look at the documentation of the $ operator and read operations in general.

ThePhysicist
  • 1,822
  • 16
  • 21
  • Ok, thanks. I still have to retrieve the object for "list" key (would have prefered to get directly the array), but this is probably the only way currently. – User Aug 26 '13 at 09:00