I have some data structure like this
{
a: 1,
array1: [
{
b: 2
array2: [
{
// this is my target
c: 3,
d: 3
},
{
c: 4,
d: 4
}
]
},
{
b: 3
array2: [
{
c: 5,
d: 5
},
{
c: 6,
d: 6
}
]
}
]
}
I know use {"array1" : {"$elemMatch" : {"b" : 2} } }
to match element of first level array1. But I don't know how to match element {c: 3, d: 3}
of array2 of array1.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
This will match any document which has an array element with both 313 and either 6 or 19. It also works with {$in:[]} for both defindex and _particleEffect, as long as you intend to match any combination of the two lists. Save this answer.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
$elemMatch
is used to state association among multiple fields within the same nested structure.
For eg. If you are looking to query c and d and need them to belong to the same sub-document, the you can query it like.
{"array1.array2" : {"$elemMatch" : {"c" : 3, "d":3} } }
Note: if you are querying on a single field, you dont really need to use $elemMatch
(since there is no association)
For instance, in your query example, you can instead do
{"array1.b" : 2}
try this,it help me a lot.
{
"array1": {
"$elemMatch": {
"array2": {
"$elemMatch": {
"c": 3
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With