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