[英]How do I do a '$all $in' on mongodb?
I have the following collection 我有以下收藏
>db.prueba.find({})
{ "_id" : "A", "requi" : null }
{ "_id" : "B", "requi" : null }
{ "_id" : "C", "requi" : [ "A" ] }
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "E", "requi" : [ "C" ] }
{ "_id" : "F", "requi" : [ "B", "D"] }
{ "_id" : "G", "requi" : [ "F" ] }
I need each element of the requi field to be in the following array. 我需要requi字段的每个元素都在以下数组中。 in this case, the array has only one element 在这种情况下,数组只有一个元素
["A", "D"]
When I use the operator $all $in
returns the following 当我使用运算符$all $in
返回以下内容
>db.prueba.find({requi:{$elemMatch:{$in:['A','D']}}})
{ "_id" : "C", "requi" : [ "A" ] }
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "F", "requi" : [ "B", "D" ] }
the query must returns only document, because 'B'
not exists in the array ["A" , "D"]
查询必须仅返回文档,因为数组["A" , "D"]
不存在'B'
{ "_id" : "C", "requi" : [ "A" ] }
please, help me 请帮我
You can use $setIsSubset
to check whether the given array is set of the requi
array and then $redact
to eliminate the non-matched ones. 您可以使用$setIsSubset
检查给定数组是否选择的requi
数组,然后$redact
要消除非匹配的。
db.collection.aggregate([
{ "$match": { "requi": { "$ne": null } } },
{ "$redact": {
"$cond": {
"if": { "$eq": [{ "$setIsSubset": ["$requi", ["A", "D"]] }, true] },
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.