If I have the following 3 documents. How can I select the documents that have at least two purple squares. In this case it would only be the last element.
I know I can select documents with any purple squares with db.foo.find({foo: {"$elemMatch": {shape: "square", color: "purple"}}})
But is there a way to say it must match a certain number of times?
// 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
}
] }
This example is adapted from the last sample here: http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
This could be accomplished by using $where, MapReduce, or your application could increment a count of interesting objects when inserted/updated (e.g.
db.foo.insert({foo:[{...}, {...}, ...], purpleSquareCount:2});).The simplest solution is likely to use $where (note the performance implications):