there is a nested mongodb document that looks like the image below. I want to do a search in the body field in this document, but I could not succeed. how can i do this search. thanks in advance
I tried to search like this. Is my path correct?
const result = await this.campaignModel.find({
"sequencesPageData": {
"$elemMatch": {
"mailSteps": {
"$elemMatch": {
"mailTemplate": x
}
}
}
}
});
I did a search like this but got no results.
const result = await this.campaignModel.find({
"sequencesPageData": {
"$elemMatch": {
"mailSteps": {
"$elemMatch": {
"mailTemplate": x
}
}
}
}
});
2
Answers
For object fields, simply access them using dot notation. For array fields, use
$elemMatch
to perform the match.Mongo Playground
If you are only testing a single field in the array, there is no need to use $elemMatch, you can use dot notation:
$elemMatch is useful to ensure that 2 or more tests are satisfied by the same array element, but since this example uses only 1 test, it works without.