2013-03-08 93 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