skip to Main Content

I have a MongoDB document with the following attributes:

{
  "label": [
    "ibc",
    "ibd",
    "ibe"
  ],
  "location": "vochelle st"
}

and I have to return the document only if the documents label exactly matches the given array i.e., ["ibc","ibd"] and for the same, I am using the query:

db.collection.find({"location":"vochelle st","dock_label":{"$all":["ibc", "ibd"]}})

Actual Response:

{
  "label": [
    "ibc",
    "ibd",
    "ibe"
  ],
  "location": "vochelle st"
}

Expected Response:

{}

Since the label "ibe" doesn’t exist in the given array, the expected result has to be the empty dictionary.

3

Answers


    1. Use $setIntersection to intersect both label and input array.
    2. Compare both intersected array (from 1) and label arrays are matched via $eq.
    db.collection.find({
      "location": "vochelle st",
      $expr: {
        $eq: [
          {
            $setIntersection: [
              "$label",
              [
                "ibc",
                "ibd"
              ]
            ]
          },
          "$label"
        ]
      }
    })
    

    Sample Mongo Playground

    Login or Signup to reply.
  1. Give $size in your query

    db.collection.find({
      location: "vochelle st",
      label: {
        $all: [
          "ibc",
          "ibd"
        ],
        $size: 2
      }
    })
    

    mongoplayground

    Login or Signup to reply.
  2. If you want to check if the array exactly matches your input, you don’t need any operator, just compare it with your value:

    db.collection.find({"location":"vochelle st","label": ["ibc", "ibd"]}) 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search