有条件地放松MongoDb的聚合? [英] Conditional unwind in MongoDb's aggregation?
问题描述
我正在尝试找出是否有一种方法可以在MongoDB的聚合框架中编写条件展开的代码.
I'm trying to figure out if there is a way to code a conditional unwind in MongoDB's aggregation framework.
我有一个这样的聚合命令:
I have an aggregation command like this:
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) {
(...)
});
我想按部门添加可选的过滤器.一个用户可以在一个或多个部门中,这就是数据库中的样子:
I'd like to add an optional filter by department. A user can be in one or more departments, here is how it looks like in the db:
用户 _ID 性别 salesIndex 部门{[d1,d2,d3]}
user _id sex salesIndex departments {[d1, d2, d3]}
如果我想搜索特定部门中的用户,我会先编写$ unwind子句,然后再按部门编写$ match.但是,我想在两种情况下使用相同的聚合命令,如下所示:
If I wanted to search for users in a particular department, I'd code an $unwind clause and then a $match by department. However I'd like to use the same aggregation command for both scenarios, something like this:
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个聚合命令?
Is this possible at all, or I need 2 aggregation commands?
推荐答案
以编程方式在调用aggregate
之前建立聚合管道:
Build up your aggregation pipeline programmatically prior to calling 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) {
//...
});
这篇关于有条件地放松MongoDb的聚合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!