MongoDB $ and query on several fields and values ​​inside one embedded document

I am looking for a way to request a collection as follows:

[{ name: "Parent 1", items: [ { name: "Child 1", age: "60" }, { name: "Child at heart", age: "27" } ] }, { name: "Parent 2", items: [ { name: "Child 3", age: "10" }, { name: "Child 4", age: "15" }, { name: "Child at heart", age: "60" } ] } ] 

With such a request:

 db.collection.find( 'items.name' => "Child at heart", 'items.age' => "60" ) 

And get the result of only the object named "Parent 2". That is, I want to query documents that search for those that contain an inline element that has both the name “Child at heart” and age “60” in the same inline document. Instead, this query returns both documents: “Parent 1” and "Parent 2".

How do I execute a query using $ and conditions for different fields inside the same embedded document?

Thanks.

+6
source share
1 answer

The problem is that $and accepts every condition, applies it to all embedded documents and counts the document as satisfying the condition if any embedded document matches. This does not correlate with conditions.

Required operator $elemMatch . It performs the correlation you are looking for. Here is the correct request:

 db.collection.find({items: {$elemMatch: {name: 'Child at heart', age: '60'} }}) 

items is the name of the array you want to find.

Query request for sample data:

 { "_id" : ObjectId("51a012f0ac3dfe4f0c05ca89"), "name" : "Parent 2", "items" : [ { "name" : "Child 3", "age" : "10" }, { "name" : "Child 4", "age" : "15" }, { "name" : "Child at heart", "age" : "60" } ] } 
+9
source

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