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

Mongodb query collection's array contains all element in input array

Let say I have those document like bellow

[
    {
        array : ['a', 'b' , 'c'],
    },
    {
        array : ['b', 'd' , 'e'],
    },
    {
        array : ['d', 'e' , 'f'],
    },
]

and input array for query

["b","d","e","f"]

expect output :

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

['b', 'd' , 'e'],['d', 'e' , 'f']

Which query can I use to do that?
And how to filter which element is not in the document?
expect :

[
 {
   array : ['b', 'd' , 'e'],
   missingElement : ['f']
 },{
   array : ['d', 'e' , 'f'],
   missingElement : ['b']
 },
]

>Solution :

  1. $expr – Allow to use aggregation operator.

    1.1. $eq – Compare the result from 1.1.1 and 1.1.2 are equal.

    1.1.1. $size – Get the size of array field.

    1.1.2. $size – Get the size of array from the result 1.1.2.1.

    1.1.2.1. $setIntersection – Intersect array field and input array, return the intersected value(s) in array.

db.collection.find({
  $expr: {
    $eq: [
      {
        $size: "$array"
      },
      {
        $size: {
          $setIntersection: [
            "$array",
            [
              "b",
              "d",
              "e",
              "f"
            ]
          ]
        }
      }
    ]
  }
})

Sample Mongo Playground

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