这可以通过使用$其中,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});