我希望能够找到多个在数组中具有三个或更多匹配值的文档.让我们说以下文件:
[{
name: 'John',
cars: [1, 2, 3, 4]
},
{
name: 'Jane',
cars: [1, 2, 3, 8]
},
{
name: 'Smith',
cars: [1, 8, 10]
}]
Run Code Online (Sandbox Code Playgroud)
我们希望在以下数组中找到至少包含三个值(在汽车中)的文档:
[1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
结果将是:
[{
name: 'John',
cars: [1, 2, 3, 4]
},
{
name: 'Jane',
cars: [1, 2, 3, 8]
}]
Run Code Online (Sandbox Code Playgroud)
谁知道如何实现这一目标?
Sus*_*pta 13
您可以$in发出查询,然后通过代码过滤所需数组中包含3个或更多条目的记录.(这是一些samle python代码)
def dennisQuestion():
permissibleCars = [1,2,3,4,5,6,7]
cursor = db.collection.find({"cars": {"$in": permissibleCars}})
for record in cursor:
if len(set(permissible) & set(record["cars"]))) >= 3
yield record
Run Code Online (Sandbox Code Playgroud)
这是一个很好的问题,我认为有一种简单的方法可以使用MongoDB为您提供的常用运算符.但是我可以想到以下方法来实现这个目的:
1.新领域
在应用程序代码中计算此值,并将结果保存在文档的新字段中.
2.蛮力
db.Collection.find( { $or: [
{ cars: $all [ 1, 2, 3 ] },
{ cars: $all [ 2, 3, 4 ] },
... list out all 35 combinations
] } )
Run Code Online (Sandbox Code Playgroud)
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;
} } );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13271 次 |
| 最近记录: |