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:
- Use
$setIntersection
to intersect bothlabel
and input array. - 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"
]
}
})
CodePudding user response:
Give $size
in your query
db.collection.find({
location: "vochelle st",
label: {
$all: [
"ibc",
"ibd"
],
$size: 2
}
})
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"]})