4

I am trying to sum a document array with condition.

{
        $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"}
        }
    }

This is the output i am getting. Here you can see my watched array has a value with status true in it. So numberOfWatched was suppose to be 1. Instead its returning 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 Answer 1

2

You can try below $size and $filter aggregation

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" }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

3 Comments

i need to do this using $sum as i have to do the same thing with durationWatched using duration field under watched object
also seems $filter filters out the whole data that doesnt match the filter condition.
oh my bad.. Yes, its ok for numberOfWatched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.