Reputation: 298
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.
Upvotes: 15
Views: 17538
Reputation: 11445
let feed = await Doc.findOneAndUpdate(
{
$and: [
{
_id: req.params.id,
},
{
'feeds.$[].locations': {
$elemMatch: {
uniqueName,
},
},
},
],
},
{
$pull: {
//@ts-ignore
'feeds.$[].locations': { uniqueName },
},
},
{ new: true }
);
Upvotes: 0
Reputation: 16335
$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}
Upvotes: 20
Reputation: 111
try this,it help me a lot.
{
"array1": {
"$elemMatch": {
"array2": {
"$elemMatch": {
"c": 3
}
}
}
}
}
Upvotes: 11