To achieve this effectively, the recommended method is to utilize native operators like .aggregate()
along with $redact
:
db.collection.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$setIsSubset": [
{ "$map": { "input": ["A"], "as": "el", "in": "$movie" } },
"$List"
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
If $redact
is not available in your MongoDB version, another alternative is to use the $where
query condition:
db.collection.find(function() {
return this.List.indexOf(this.movie) != 1
})
Both methods focus on checking for one field value within an array field in the document.
Variations of using $redact
are possible, such as incorporating $anyElementTrue
:
db.collection.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$anyElementTrue": {
"$map": {
"input": "$List",
"as": "el",
"in": { "$eq": [ "$$el", "$movie" ] }
}
}
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
Alternatively, a concise syntax can be used in MongoDB 3.2:
db.collection.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$setIsSubset": [
["$movie"],
"$List"
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
In this case, similar to the original implementation utilizing $map
, the ["$movie"]
converts the single element into an array/set for comparison with $setIsSubset
. The latter example uses $map
to apply conditions to each element in the array, generating an array of true/false
values that are consolidated into a logical outcome via $anyElementTrue
.