Home > Software engineering >  Pymongo :: How to compare the given array exactly matches with the document?
Pymongo :: How to compare the given array exactly matches with the document?

Time:03-24

I have a mongo document with the following attributes

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

and i have to return the dcocument only if the documents label exactly matches with 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 empty dictionary.

CodePudding user response:

  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

CodePudding user response:

Give $size in your query

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

mongoplayground

CodePudding user response:

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"]}) 
  • Related