Search code examples
mongodbaggregation-framework

Array field contains array values of other field


Sample data:

db={
  "Test": [
    {
      "x": [1, 2],
      "y": [1, 2, 3]
    },
    {
      "x": [1, 2],
      "y": [2, 3, 4]
    }
  ]
}

To match static array values I can do this:

db.Test.aggregate([
  {
    "$match": {
      "y": {
        "$all": [1, 2]
      }
    }
  }
])

..to get the desired result where all values of x is in y:

[
  {
    "x": [1, 2],
    "y": [1, 2, 3]
  }
]

But I need to find arrays that have values of an array field. Tried using $all with $expr but that is not allowed:

db.Test.aggregate([
  {
    "$match": {
      "$expr": {
        "$all": [
          "$x",
          "$y"
        ]
      }
    }
  }
])

What can I do instead? Thanks.

Playground


Solution

  • Assuming that you can treat your arrays as sets with unique items, you can use the $setIsSubset operator for this, e.g.:

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            "$setIsSubset": [
              "$x",
              "$y"
            ]
          }
        }
      }
    ]);
    

    The operator returns true if the first array is a subset of set second one. For your sample, this returns the first document, but not the second.

    See this mongoplayground to test.