MongoDB按查询嵌套组

时间:2017-12-02 11:26:14

标签: mongodb mongoose mongodb-query mongoose-schema

我想要计算正确,不正确和未尝试的问题。我的价值为零。

查询 -

.mapboxgl-map .mapboxgl-popup{
    right:100px;
    bottom:100px;
    top:auto;
    left:auto;
    position:fixed;
    transform:none !important;
}
.mapboxgl-map .mapboxgl-popup-tip{display:none;}

架构结构 -

db.studentreports.aggregate([
{ $match: { 'groupId': 314 } },
{ $unwind: '$questions' },
{ $group: 
    {
      _id: {
       dateTimeStamp: '$dateTimeStamp',
       customerId: '$customerId'
      },
      questions : { $push: '$questions' },
      unttempted : { $sum : { $eq: ['$questions.status',0]}},
      correct : { $sum : { $eq: ['$questions.status',1]}}, 
      incorrect : { $sum : { $eq: ['$questions.status',2]}}, 
      Total: { $sum: 1 }      
    }
}
])

未经尝试的值,正确和不正确的错误 -

" unttempted" :0,  "正确" :0,  "不正确" :0,  "总计" :7558.0

根据datetime和customerId需要分组依据。 有人可以正确查询吗? 感谢。

1 个答案:

答案 0 :(得分:1)

您只想在满足特定条件时才对这些字段求和。 你只需要像这样重写你的组语句:

{ $group: 
    {
      _id: {
       dateTimeStamp: '$dateTimeStamp',
       customerId: '$customerId'
      },
      questions : { $push: '$questions' },
      unttempted : { $sum : {$cond:[{ $eq: ['$questions.status',0]}, 1, 0]}},
      correct : { $sum : {$cond:[{ $eq: ['$questions.status',1]}, 1, 0]}}, 
      incorrect : { $sum : {$cond:[{ $eq: ['$questions.status',2]}, 1, 0]}},
      Total: { $sum: 1 }      
    }
}

查看文档$eq$eq比较并返回true或false。那么你的$sum无法对结果做任何事情