[英]Mongo find documents where array contains x values of given array
I have a collection which has documents like that one.我有一个集合,里面有这样的文件。 The entity field is not set in each document and has different values:
每个文档中都没有设置实体字段,并且具有不同的值:
{
"_id" : ObjectId("5388cfbdec82ba7cd5438635"),
"name" : "Name1",
"entity" : [
"Entity1",
"Entity2",
"Entity4",
"Entity5"
]
}
Now I want to find all documents which contains exactly x values of the given array : ["Entity1","Entity2","Entity3","Entity4"]
现在我想找到包含给定数组的 x 值的所有文档:
["Entity1","Entity2","Entity3","Entity4"]
For the document posted above the values Entity1, Entity2, Entity4 are matching:对于上面发布的文档,Entity1、Entity2、Entity4 的值是匹配的:
You can use .aggregate
for this.您可以为此使用
.aggregate
。 This is probably what you're looking for:这可能是你正在寻找的:
var y = ["Entity1", "Entity2", "Entity3", "Entity4"];
db.col.aggregate([
{
$project :
{
_id : 1,
name : 1,
entity : 1,
x : {
$size : {
$ifNull: [{$setIntersection : ["$entity", y]}, []]
}
}
}
},
{ $match : { x : 3 } }
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.