如何在mongo聚合框架中的管道阶段之后加入文档

时间:2016-01-06 06:47:42

标签: mongodb aggregation-framework

所以,让我们说在聚合的第一阶段之后,我已经将所有文档分组到中心,所以我有这样的事情:

{
center:"A",
gender:"Male",
count:50
}
{
center:"A",
gender:"Female",
count:20
}

我想加入这两个文档,使最终文档看起来像

{
center:A,
Male:50,
Female:20
}

1 个答案:

答案 0 :(得分:0)

介绍另一个 $group 管道步骤,您可以按中心字段对传入的文档流进行分组,在组中引入使用 $sum的新字段运营商。 $sum 操作将由使用 $cond 运算符的条件确定,该运算符评估性别表达式,并根据结果返回基于评估逻辑的先前计数。

考虑以下管道延续:

db.collection.aggregate([
    /* previous pipeline(s) here ... */
    {
        "$group": {
            "_id": "$center",
            "Male": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$gender", "Male" ] }, "$count", 0 ]
                }
            },
            "Female": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$gender", "Female" ] }, "$count", 0 ]
                }
            }
        }
    },
    {
        "$project": {
            "_id": 0, "center": "$_id", "Male": 1, "Female": 1
        }
    }
])