0
I have the following array:
[
{
“user”: “USER1”,
“last”: “USER1”
},
{
“user”: “USER1”,
“last”: “USER2”
},
{
“user”: “USER2”,
“last”: “USER1”
},
{
“user”: “USER2”,
“last”: “USER2”
},
{
“user”: “USER1”,
“last”: “USER2”
},
{
“user”: “USER1”,
“last”: null
}
]
I’m performing the following consultation on mongodb:
{$group: {
_id: “$user”,
total: {$sum: 1},
last: {$sum: {$cond: [
{$eq: ['$last’, '$user']}, 1, 0
]}}
}}
I expect this result:
[
{
_id: “USER1”
total: 4,
last: 2
},
{
_id: “USER2”
total: 2,
last: 3
}
]
But I’m getting this:
[
{
_id: “USER1”
total: 4,
last: 1
},
{
_id: “USER2”
total: 2,
last: 1
}
]
I know the problem is in grouping, it only finds the last if the current user is the same.
How I can group, but at the time of counting consider all values?