【问题标题】:How to use $group and $cond together in MongoDB Aggregation?如何在 MongoDB 聚合中同时使用 $group 和 $cond?
【发布时间】:2019-07-10 04:17:26
【问题描述】:

我有如下收藏。

{
    "userId" : "1",
    "feedbackGiven" : true
}
{
    "userId" : "1",
    "feedbackGiven" : false
}
{
    "userId" : "1",
    "feedbackGiven" : true
}
{
    "userId" : "2",
    "feedbackGiven" : false
}
{
    "userId" : "2",
    "feedbackGiven" : true
}

我需要在 userId 上对此进行分组,并获得两个值作为 totalGivenFeedback 的计数和 false feedbackGiven 的计数。

我试过下面的查询。

db.collection.aggregate([
{
      $group: { _id: "$userId", feedbackGiven: { $push : "$feedbackGiven"} }
}
])

这会给出如下结果。

{
    "_id" : "1",
    "feedbackGiven" : [ 
        true, 
        false,
        true
    ]
}
{
    "_id" : "2",
    "feedbackGiven" : [ 
        false,
        true
    ]
}

使用我的 JavaScript 代码中的上述结果,我可以获得总反馈和错误反馈的计数。

但我的问题是,有没有办法使用 MongoDB 查询来获取它。

我期待如下结果。

{
    "_id" : "1",
    "totalFeedbackGive" : 3,
    "falseFeedbackCount" : 1
}
{
    "_id" : "2",
    "totalFeedbackGive" : 1,
    "falseFeedbackCount" : 1
}

谁能给我一个解决方案?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以在下面使用aggregation

    db.collection.aggregate([
      { "$group": {
        "_id": "$userId",
        "totalFeedbackGive": { "$sum": 1 },
        "falseFeedbackCount": {
          "$sum": {
            "$cond": [
              { "$eq": ["$feedbackGiven", false] },
              1,
              0
            ]
          }
        }
      }}
    ])
    

    所以你需要使用$sum累加器来统计应用$group阶段后的文档数。

    其次,您需要使用 $sum 累加器 $conditionally 来计算 falseFeedback 计数的文档数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-17
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2015-05-25
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多