【问题标题】:How to join documents after a pipeline stage in mongo aggregation framwork如何在mongodb聚合框架中的管道阶段后加入文档
【发布时间】:2016-01-06 06:47:41
【问题描述】:

所以可以说在第一阶段聚合之后,我按中心对所有文档进行了分组,所以我有这样的东西:

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

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

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

【问题讨论】:

  • 您能否提供示例文档以及您到目前为止所做的尝试?
  • 提供您的原始架构,有可能一步到位。

标签: mongodb aggregation-framework


【解决方案1】:

引入另一个 $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
        }
    }
])

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多