有条件求和mongodb聚合

时间:2018-09-29 10:25:36

标签: mongodb mongoose aggregation-framework

我正在尝试对有条件的文档数组求和。

{
        $project: {
            watched: 1,
            numberOfWatched: {
                $sum: {
                    // $cond: {
                    //     if: {
                    //         $eq: ['$watched.status', true],
                    //         then: 1,
                    //         else: 0
                    //     }
                    // }
                       $cond: [
                        { $eq: ['$watched.status', true]},
                        1,
                        0
                    ]
                }
            },
            durationWatched: {$sum: "$watched.duration"}
        }
    }

这是我得到的输出。在这里,您可以看到我监视的数组中有一个状态为true的值。因此,numberOfWatched假定为1。相反,它返回0。

[
   {
      "_id":"5bacb579921406542350d254",
      "watched":[
         {
            "_id":"5baf44ee2369280542a4c41e",
            "duration":24.083333333333332,
            "user_id":"5bacbb05d2b8e4577b038f43",
            "video_id":"5bacb5b1921406542350d25e",
            "module_id":"5bacb588921406542350d256",
            "course_id":"5bacb579921406542350d254",
            "createdAt":"2018-09-29T09:25:02.107Z",
            "updatedAt":"2018-09-29T09:25:02.107Z",
            "__v":0,
            "status":true
         }
      ],
      "numberOfWatched":0,
      "durationWatched":24.083333333333332
   }
]

1 个答案:

答案 0 :(得分:0)

您可以尝试以下$size$filter聚合

db.collection.aggregate([
  { "$project": {
    "watched": 1,
    "numberOfWatched": {
      "$size": {
        "$filter": {
          "input": "$watched",
          "cond": { "$eq": [ "$$this.status", true ] }
        }
      }
    },
    "durationWatched": {
      "$let": {
        "vars": {
          "dw": {
            "$filter": {
              "input": "$watched",
              "cond": { "$eq": [ "$$this.status", true ] }
            }
          }
        },
        "in": { "$sum": "$$dw.duration" }
      }
    }
  }}
])