问题
I am a mongo noob and am working with a mongo collection with records that look like so:
{
"cats" [
{
"name": "fluffy",
"color": "red",
},
{
"name": "snowball",
"color": "white",
},
]
{
I would like to perform a query that gets all records that have more than 1 white cats. MapReduce looks promising, but seems like overkill. Any help is appreciated.
回答1:
You can use the aggregation framework to do this. You don't need to use the $where operator.
db.collection.aggregate([
{ "$match": { "cats.color": "white" }},
{ "$project": {
"nwhite": { "$map": {
"input": "$cats",
"as": "c",
"in": { "$cond": [
{ "$eq": [ "$$c.color", "white" ] },
1,
0
]}
}},
"cats": 1
}},
{ "$unwind": "$nwhite" },
{ "$group": {
"_id": "$_id",
"cats": { "$first": "$cats" },
"nwhite": { "$sum": "$nwhite" }
}},
{ "$match": { "nwhite": { "$gte" :2 } } }
])
回答2:
Use $where. It is an especially powerful operator as it allows you to execute arbitrary javascript.
For your specific case, try this:
db.collection.find({$where: function() {
return this.cats.filter(function(cat){
// Filter only white cats
return cat.color === 'white';
}).length >= 2;
}});
来源:https://stackoverflow.com/questions/32484001/get-documents-with-nested-objects-matching-count-condition