What if we could filter the array only, but instead of returning the filtered array as the result, use it to override the original one? Turns out we can:
db.getCollection('posts').aggregate(
{$match: {"author.id": authorId}},
{$addFields : {"comments":{$filter:{ // We override the existing field!
input: "$comments",
as: "comment",
cond: {$eq: ["$$comment.state.deleted", false]}
}}}}
);
That's it. This little trick allows nested array filtering. I also suspect that I could patch it for nested nested array filtering, but that's for another post.
B.t.w the results:
{
"author": {},
"message": "This is post1",
"comments": [
{
"message": "Im number 1!!!",
"state": {
"deleted": false
}
},
{
"message": "tHIS IS GREAT!",
"state": {
"deleted": false
}
},
{
"message": "I can type better than you guys",
"state": {
"deleted": false
}
}
]
},
{
"author": {},
"message": "This is post 2",
"comments": [
{
"message": "I wanna have your children",
"state": {
"deleted": false
}
}
]
}
Comments
Post a Comment