I have managed to create an aggregate which returns two array in a document like so:
"b": [
{
"_id": "6258bdfe983a2d31e1cc6a4b",
"booking_room_id": "619395ba18984a0016caae6e",
"checkIn_date_time": "2022-04-16",
"checkOut_date_time": "2022-05-17"
}
]
"r": [
{
"_id": "619395ba18984a0016caae6e",
}
]
I want to remove the item from r
if _id
in r
matches booking_room_id
in b
.
Also, since these array exist inside a parent document. I want to remove the parent document from the query if r
is empty after performing the filter.
CodePudding user response:
Use $expr
and $filter
db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
{
$filter: {
input: "$r",
as: "r",
cond: {
$not: { $in: [ "$$r._id", "$b.booking_room_id" ] }
}
}
},
[]
]
}
}
},
{
$set: {
r: {
$filter: {
input: "$r",
as: "r",
cond: {
$not: { $in: [ "$$r._id", "$b.booking_room_id" ] }
}
}
}
}
}
])