Search code examples
mongodbaggregation-frameworkmatchprojection

MongoDB match array based on document value rather than explicit condition


Let's say I have the following document structure:

{
  "A": {
    "_id": "ID0"
  },
  "B": [
    {
      "_id": "ID0",
      "field": "X"
    },
    {
      "_id": "ID1",
      "field": "Y"
    }
  ]
}

I want to project B matched with the _id in A. The end result would be:

{
  "B": [
    {
      "_id": "ID0",
      "field": "X"
    }
  ]
}

I tried the following but apparently I'm doing something wrong. Is it possible to match based on a document filed rather than an explicit condition?

db.collection.aggregate([
  {$match: {"B._id": "$A._id"}},
  {$project: {"B": 1}}
])

Solution

  • You can use $filter aggregation operator to achieve this :

    db.collection.aggregate([
      {
        $addFields: {
          "B": {
            $filter: {
              input: "$B",
              as: "arr",
              cond: {
                $eq: [
                  "$A._id",
                  "$$arr._id"
                ]
              }
            }
          }
        }
      }
    ])
    

    Test it here