How to get only those docs which has all the match fields in mongoose
-
22-02-2021 - |
Question
Let say I have the following collection named survey
:
{ _id: 1, results: [ { product: "abc", active: true}, { product: "xyz", active: true} ] }
{ _id: 2, results: [ { product: "abc", active: false }, { product: "xyz", active: true } ] }
{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }
by doing:
db.survey.find(
{ results: { $elemMatch: { active: false } }
)
I will get all the docs where at least one object in the array is false i.e.
{ _id: 2, results: [ { product: "abc", active: false }, { product: "xyz", active: true } ] }
{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }
but how can I get only those docs which has all the key active: false
i.e:
{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }
TIA..
Solution
so here I got one solution, which is perfectly apt for my need:
db.getCollection('survey').aggregate([
{ "$match": { "results.active": false } },
{ "$redact": {
"$cond": {
"if": {
"$allElementsTrue": {
"$map": {
"input": "$results",
"as": "result",
"in": { "$eq": [ "$$result.active", false ] }
}
}
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange