聚合计数逻辑值

时间:2017-08-15 05:28:50

标签: mongodb aggregation-framework

你好朋友我对mongodb聚合不友好我想要的是我有一个对象数组,其中包含每个问题得分的主题,我正在使用节点js所以我想要的是mongo查询的完整计算,如果可能的话,包括主题名称及其总分和尝试次数,而不是尝试我的Json数组如下所示

{
    "examId": ObjectId("597367af7d8d3219d88c4341"),
    "questionId": ObjectId("597368207d8d3219d88c4342"),
    "questionNo": 1,
    "subject": "Reasoning Ability",
    "yourChoice": "A",
    "correctMark": "1",
    "attempt": true,
    "notAttempt": false,
}

这里的对象一个字段是正确的标记主题是不同的我想要输出像

|Subject Name | Total attempts | total not attempts | total score |
| A           | 5              | 3                  | 10          |
| B           | 10             | 5                  | 25          |

我正在尝试使用聚合但尚未完成但我已尝试过此查询

db.examscores.aggregate([
  { $group:{
    _id:"$examId",
    score: { $sum: '$correctMark' },
    count: { $sum: 1 }
  }}
])

任何人都知道如何实现这种类型的输出。 如果使用节点实现此目的的另一种方式也不错。

1 个答案:

答案 0 :(得分:0)

我在这里解决了这个问题

[
 { $match: { subject:'Reasoning Ability' } },
 {
   $group:
     {
       _id:{id:"$examId",subject:'$subject'},
       totalAttempt: { $sum:  {$cond : [ "$attempt", 1, 0 ]} },
       totalNotAttempt: { $sum:  {$cond : [ "$notAttempt", 1, 0 ]} },
       markedForReview:{ $sum:  {$cond : [ "$markedForReview", 1, 0 ]} },
       answerAndMarkedForReview:{ $sum:  {$cond : [ "$answerAndMarkedForReview", 1, 0 ]} },
       score: { $sum: '$correctMark' },
       count: { $sum: 1 }
     }
 }