如何在MongoDB聚合中一起使用$ group和$ cond?

时间:2019-07-10 04:17:26

标签: mongodb mongodb-query aggregation-framework

我有如下收藏。

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

我需要在 userId 上对其进行分组,并获得两个值,分别是totalGivenFeedback计数和错误反馈Given计数。

我在下面的查询中尝试过

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
}

谁能给我解决方案?

1 个答案:

答案 0 :(得分:1)

您可以在aggregation下使用

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

因此,在应用$sum阶段之后,您需要使用$group累加器来计算文档数。

第二步,您需要使用$sum累加器$condfalseFeedback计数的文档数进行计数