Search code examples
arraysmongodbmongodb-querypymongo

PyMongo - How to compare the given array exactly matches with the document


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.


Solution

  • Give $size in your query

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

    mongoplayground