如何根据数组中匹配对象的数量在MongoDb中查找文档

时间:2012-02-10 23:08:52

标签: mongodb

如果我有以下3个文件。如何选择至少有两个紫色方块的文档。在这种情况下,它只是最后一个元素。

我知道我可以选择带有db.foo.find({foo: {"$elemMatch": {shape: "square", color: "purple"}}})

的紫色方块的文档

但有没有办法说它必须匹配一定次数?

// 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
      }
] }

此示例改编自此处的最后一个示例:http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29

2 个答案:

答案 0 :(得分:1)

这可以通过使用$ where,MapReduce或您的应用程序在插入/更新时增加有趣对象的数量来实现(例如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});

答案 1 :(得分:0)

仅通过$where

相关问题