如何使用聚合对值为 true 的字段求和

How sum fields with the value true using aggregate

Model.aggregate([
   {
    '$group': {
       '_id': '$id',
       'name': { '$first': '$name'  },
       'tof': { $sum: { $eq:["$tof",true] } },
    }
   }
]) .... // rest of the code.

我正在尝试对 tof(true 或 false)字段求和,但前提是值为 true,但不像我尝试的那样工作..

我做错了什么?如何进行?

谢谢!!

不需要像在本例中那样提取和迭代,而是使用 $cond 不需要的文档,您可以从查找中省略它们:

Model.aggregate([
   {
      '$match': {'tof': true}
   },
   {
    '$group': {
       '_id': '$id',
       'name': { '$first': '$name'  },
       'tof': { $sum: 1 },
    }
   }
])

但是,由于您使用的是多个计数,因此您需要 $cond ( http://docs.mongodb.org/manual/reference/operator/aggregation/cond/ ),所以这里有一个示例:

Model.aggregate([
   {
    '$group': {
       '_id': '$id',
       'name': { '$first': '$name'  },
       'tof': { $sum: {$cond: [{$eq:['$tof', true]}, 1, 0]} },
    }
   }
])