'Pymongo :: How to compare the given array exactly matches with the document?
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.
Solution 1:[1]
Give $size in your query
db.collection.find({
location: "vochelle st",
label: {
$all: [
"ibc",
"ibd"
],
$size: 2
}
})
Solution 2:[2]
- Use
$setIntersectionto intersect bothlabeland input array. - Compare both intersected array (from 1) and
labelarrays are matched via$eq.
db.collection.find({
"location": "vochelle st",
$expr: {
$eq: [
{
$setIntersection: [
"$label",
[
"ibc",
"ibd"
]
]
},
"$label"
]
}
})
Solution 3:[3]
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"]})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | YuTing |
| Solution 2 | Yong Shun |
| Solution 3 | David SN |
