Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - $filter 2 array contains object

Let's say I have a document like bellow

{
  fieldA : [
    {
      _id : 1,
      value : 1,
    },
    {
      _id : 2
      value : 2,
    },
    {
      _id : 3,
      value : 3,
    },
  ],
  fieldB : [
    {
      _id : 2
    },
    {
      _id : 3
    },
    {
      _id : 4
    },
  ],
  
}

I want to filter which _id in fieldB has in fieldA and take value in fieldA, add to new field name fieldC

Expected output

  fieldC : [
    {
      _id : 2,
      value : 2,
    },
    {
      _id : 3,
      value : 3,
    },
  ]

I tried using $filter in $addFields but it returned an empty array

{
  $addFields : {
    fieldC : {
      $filter : {
        input : "$fieldB",
        cond : {
          $in : ["$$this._id", "$fieldA._id"]
        }
      }
    }
  }
}
fieldC = []
like image 598
vy.pham Avatar asked Apr 28 '26 05:04

vy.pham


1 Answers

From my understanding, your expected behaviour is actually a set intersection behaviour. You may simply "swap" your $filter to do a._id in b._id.

db.collection.aggregate([
  {
    "$addFields": {
      "fieldC": {
        "$filter": {
          "input": "$fieldA",
          "as": "a",
          "cond": {
            "$in": [
              "$$a._id",
              "$fieldB._id"
            ]
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

like image 160
ray Avatar answered Apr 30 '26 20:04

ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!