How to get a nested object?

I have a collection with the following documents:

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

How to get this object: {id:1} ?

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

it finds the record, but returns the full document instead of {id:1}

+4
source share
1 answer

The $ operator is what you are 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 do not need the _id of the document, you can also exclude it:

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

For more information, see the documentation for $ operator and read operations in general.

+4
source

Source: https://habr.com/ru/post/1498868/


All Articles