MongoDb聚合中的条件展开?

时间:2012-12-12 13:18:32

标签: mongodb mongoose aggregation-framework

我正在试图弄清楚是否有办法在MongoDB的聚合框架中编写条件展开。

我有一个像这样的聚合命令:

models.Users.aggregate(
        {   // SELECT
        $project : { "sex" : 1,
                 "salesIndex":1
                }
        },
        {   // WHERE
            $match: {"salesIndex": {$gte: index}} 
        },              
        {   // GROUP BY y agregadores
            $group: {
                _id      : "$sex",
                sexCount : { $sum: 1 }
            }
        },
        { $sort: { sexCount: -1 } }
, function(err, dbres) {
         (...)
});

我想按部门添加可选过滤器。用户可以在一个或多个部门中,这是它在db中的样子:

用户       _ID       性别       salesIndex       部门{[d1,d2,d3]}

如果我想搜索特定部门的用户,我会编写$ unwind子句,然后按部门编写$ match。但是,我想对两种情况使用相同的聚合命令,如下所示:

models.Users.aggregate(
        {   // SELECT
        $project : { "sex" : 1,
                 "salesIndex":1
                }
        },
        {   // WHERE
            $match: {"salesIndex": {$gte: index}} 
        },  

                    IF (filteringByDepartment){

                        $unwind departments here                            
                        $match by departmentId here
                    } 

        {   // GROUP BY y agregadores
            $group: {
                _id      : "$sex",
                sexCount : { $sum: 1 }
            }
        },
        { $sort: { sexCount: -1 } }
, function(err, dbres) {
         (...)
});

这是否可行,或者我需要2个聚合命令?

1 个答案:

答案 0 :(得分:7)

在调用aggregate之前以编程方式构建汇总管道:

 
var pipeline = [];
pipeline.push(
    {   // SELECT
    $project : { "sex" : 1,
             "salesIndex":1
            }
    },
    {   // WHERE
        $match: {"salesIndex": {$gte: index}}
    }
);
if (filteringByDepartment) {
    pipeline.push(
        { $unwind: '$departments' },
        { $match: { departments: departmentId }}
    );
}    
pipeline.push(
    {   // GROUP BY y agregadores
        $group: {
            _id      : "$sex",
            sexCount : { $sum: 1 }
        }
    },
    { $sort: { sexCount: -1 } }
);

models.Users.aggregate(pipeline, function(err, dbres) {
    //...
});