MongoDB-匹配数组中的多个值
我希望能够在一个数组中找到具有三个或更多匹配值的多个文档。假设我们已经收到了以下文件:MongoDB-匹配数组中的多个值,mongodb,find,Mongodb,Find,我希望能够在一个数组中找到具有三个或更多匹配值的多个文档。假设我们已经收到了以下文件: [{ name: 'John', cars: [1, 2, 3, 4] }, { name: 'Jane', cars: [1, 2, 3, 8] }, { name: 'Smith', cars: [1, 8, 10] }] 我们希望在以下数组中找到至少有三个值(以汽车为单位)的文档:
[{
name: 'John',
cars: [1, 2, 3, 4]
},
{
name: 'Jane',
cars: [1, 2, 3, 8]
},
{
name: 'Smith',
cars: [1, 8, 10]
}]
我们希望在以下数组中找到至少有三个值(以汽车为单位)的文档:
[1, 2, 3, 4, 5, 6, 7]
结果将是:
[{
name: 'John',
cars: [1, 2, 3, 4]
},
{
name: 'Jane',
cars: [1, 2, 3, 8]
}]
有人知道如何实现这一点吗?这是一个好问题,我不认为有一种简单的方法可以使用MongoDB提供的常用操作符实现这一点。然而,我可以想出以下方法来实现这一点: 1。新字段 计算此应用程序内代码,并将结果保存在文档的新字段中 2。蛮力
db.Collection.find( { $or: [
{ cars: $all [ 1, 2, 3 ] },
{ cars: $all [ 2, 3, 4 ] },
... list out all 35 combinations
] } )
3。使用$where
db.Collection.find( { cars: { $in: [1,2,3,4,5,6,7] }, $where: function() {
var numMatches = 0;
for (var i = 1; i <= 7; i++)
if (this.cars.indexOf(i) > -1) numMatches++;
return numMatches >= 3;
} } );
db.Collection.find({cars:{$in:[1,2,3,4,5,6,7]},$where:function(){
var numMatches=0;
对于(var i=1;i-1)numMatches++;
返回数值>=3;
} } );
您可以在查询中发出一个$,然后按代码筛选所需数组中有3个或更多条目的记录。(以下是一些样例python代码)
当Mongo 4.0.3中字符串所在的值:
db.Collection.find( { cars: { $in: ["s1", "s2", "s3" , "s4", "s5" , "s6" , "s7"] },
$where: function() {
var options = ["s1", "s2", "s3" , "s4", "s5" , "s6" , "s7"];
var numMatches = 0;
for (var i = 0; i < 7; i++)
if (this.cars.indexOf(options[i]) > -1)
numMatches++;
return numMatches >= 3;
}
} );
db.Collection.find({cars:{$in:[“s1”、“s2”、“s3”、“s4”、“s5”、“s6”、“s7”]),
$where:function(){
var选项=[“s1”、“s2”、“s3”、“s4”、“s5”、“s6”、“s7”];
var numMatches=0;
对于(变量i=0;i<7;i++)
如果(此.cars.indexOf(选项[i])>-1)
numMatches++;
返回数值>=3;
}
} );
(这对于评论来说似乎有点大)对于Mongo v4.4.1,此查询有效
[
{
$project: {
name: 1,
cars: 1,
show: {
$let: {
vars: {
"b": {
$gte: [{$size: {$setIntersection: [ [1,2,3,4,5,6,7],"$cars"]}},3]
}
},
in: "$$b"
}
}
}
},
{
$match: {
show: true,
}
},
{
$project: {
show: 0
}
}
]
[
{
$project: {
name: 1,
cars: 1,
show: {
$let: {
vars: {
"b": {
$gte: [{$size: {$setIntersection: [ [1,2,3,4,5,6,7],"$cars"]}},3]
}
},
in: "$$b"
}
}
}
},
{
$match: {
show: true,
}
},
{
$project: {
show: 0
}
}
]