2013-03-08 91 views
8

我希望能够在数组中找到多个具有三个或更多匹配值的文档。比方说,我们的下列文件:MongoDB - 匹配数组中的多个值

[{ 
     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] 
    }] 

任何人都知道如何做到这一点?

+0

+1很好的问题。我也习惯了这个时间:) – 2013-03-08 22:12:01

回答

7

这是一个很好的问题,我不认为有一种简单的方法可以通过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; 
} }); 
11

你可以有一个$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 
+1

这是真正的答案 – 2013-08-13 08:51:08