2012-02-10 52 views
2

如果我有以下3个文档。我如何选择至少有两个紫色正方形的文档。在这种情况下,它只是最后一个元素。如何根据数组中匹配对象的数量在MongoDb中查找文档

我知道我可以与任何紫色的正方形与db.foo.find({foo: {"$elemMatch": {shape: "square", color: "purple"}}})

选择文件但是,有没有办法可以说必须在一定的次数相匹配? http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29

回答

1

这可以通过使用$其中,MapReduce的,或者您的应用程序可能会增加有趣的东西计数来完成:

// Document 1 
{ "foo" : [ 
     { 
     "shape" : "square", 
     "color" : "purple", 
     "thick" : false 
     }, 
     { 
     "shape" : "circle", 
     "color" : "red", 
     "thick" : true 
     } 
] } 


// Document 2 
{ "foo" : [ 
     { 
     "shape" : "square", 
     "color" : "red", 
     "thick" : true 
     }, 
     { 
     "shape" : "circle", 
     "color" : "purple", 
     "thick" : false 
     } 
] } 

// Document 3 
{ "foo" : [ 
     { 
     "shape" : "square", 
     "color" : "purple", 
     "thick" : false 
     }, 
     { 
     "shape" : "square", 
     "color" : "purple", 
     "thick" : true 
     } 
] } 

这个例子从最后一个样本在这里适应当插入/更新时(例如db.foo.insert({foo:[{...}, {...}, ...], purpleSquareCount:2});)。

最简单的解决方案是可能使用$where(注意对性能的影响):

hasPurpleSquares = function() { 
    var count = 0; 
    this.foo.forEach(function (obj) { 
     if (obj.shape == "square" && obj.color == "purple") { 
       count = count + 1; 
     } 
    }); 
    if (count >= 2) { 
     return true; 
    } 
} 

db.foo.find({$where:hasPurpleSquares}); 
相关问题