Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading