这是集合结构
[{
"_id" : "....",
"name" : "aaaa",
"level_max_leaves" : [
{
level : "ObjectIdString 1",
max_leaves : 4,
}
]
},
{
"_id" : "....",
"name" : "bbbb",
"level_max_leaves" : [
{
level : "ObjectIdString 2",
max_leaves : 2,
}
]
}]
level_max_leaves.level
当过滤器与给定的输入值匹配时,我需要找到过滤器的子文档值。
这就是我尝试的方式,
For example,
var empLevelId = 'ObjectIdString 1' ;
MyModel.aggregate(
{$unwind: "$level_max_leaves"},
{$match: {"$level_max_leaves.level": empLevelId } },
{$group: { "_id": "$level_max_leaves.level",
"total": { "$sum": "$level_max_leaves.max_leaves" }}},
function (err, res) {
console.log(res);
});
但是这里的$match
过滤器不起作用。我找不到确切的结果ObjectIdString 1
name
如果我用字段过滤,它工作正常。像这样,
{$match: {"$name": "aaaa" } },
但在子文档级别它的回报0
。
{$match: {"$level_max_leaves.level": "ObjectIdString 1"} },
我的预期结果是,
{
"_id" : "ObjectIdString 1",
"total" : 4,
}