Reputation: 1307
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
}
]
Upvotes: 4
Views: 2624
Reputation: 46451
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" }
}
}
}}
])
Upvotes: 2