Reputation: 32267
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}
Upvotes: 4
Views: 105
Reputation: 1862
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.
Upvotes: 4