0

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.

1 Answer 1

1

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" ] }
          }
        }
      }
    }
  }
])

mongoplayground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.