1

我有如下收藏。

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

我需要在userId上对它进行分组,并获得两个值作为 totalGivenFeedback 的计数和错误的 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
}

谁能给我一个解决方案?

4

1 回答 1

1

你可以在下面使用aggregation

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

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

其次,您需要使用$sum累加器$cond来计算文档的数量以进行falseFeedback计数

于 2019-07-10T04:27:20.640 回答