获取嵌套对象匹配计数条件的文档
Get documents with nested objects matching count condition
我是一个 mongo 菜鸟,正在使用一个 mongo 集合,其中的记录如下所示:
{
"cats" [
{
"name": "fluffy",
"color": "red",
},
{
"name": "snowball",
"color": "white",
},
]
{
我想执行一个查询,以获取包含超过 1 只白猫的所有记录。 MapReduce 看起来很有前途,但似乎有点矫枉过正。感谢任何帮助。
使用$where
。它是一个特别强大的运算符,因为它允许您执行任意 javascript.
对于你的具体情况,试试这个:
db.collection.find({$where: function() {
return this.cats.filter(function(cat){
// Filter only white cats
return cat.color === 'white';
}).length >= 2;
}});
您可以使用 aggregation framework to do this. You don't need to use the $where
运算符。
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 } } }
])
我是一个 mongo 菜鸟,正在使用一个 mongo 集合,其中的记录如下所示:
{
"cats" [
{
"name": "fluffy",
"color": "red",
},
{
"name": "snowball",
"color": "white",
},
]
{
我想执行一个查询,以获取包含超过 1 只白猫的所有记录。 MapReduce 看起来很有前途,但似乎有点矫枉过正。感谢任何帮助。
使用$where
。它是一个特别强大的运算符,因为它允许您执行任意 javascript.
对于你的具体情况,试试这个:
db.collection.find({$where: function() {
return this.cats.filter(function(cat){
// Filter only white cats
return cat.color === 'white';
}).length >= 2;
}});
您可以使用 aggregation framework to do this. You don't need to use the $where
运算符。
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 } } }
])