'Mongoose - Return object only if condition matches all the objects in array
Description:
I want to only return if all the objects in the array match the condition. Now, it's returning the object if at least one condition matches in the array of objects.
If you guys have any more queries regarding this question. I will answer please ask!
Input:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
},
{
"_id":"5",
"intends":[
{
"_id":"3",
"status":"Packed"
},
{
"_id":"4",
"status":"Created"
}
]
}
]
Current Output:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
},
{
"_id":"5",
"intends":[
{
"_id":"3",
"status":"Packed"
},
{
"_id":"4",
"status":"Created"
}
]
}
]
Expected Output:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
}
]
I have tried:
db.collection.find({intends.status: "Packed"})
db.collection.find({intends: {$elemMatch: {status: "Packed"}}})
Solution 1:[1]
using aggregation $redact and $allElementsTrue
test it at mongoPlayground
db.collection.aggregate([
{
"$redact": {
"$cond": [
{
"$allElementsTrue": {
"$map": {
"input": "$intends",
"as": "intend",
"in": {
"$eq": [
"$$intend.status",
"Packed"
]
}
}
}
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 1sina1 |
