I have two collections users
and tasks
and I want to sort the users
by the sum of tasks that they created in tasks
collection.
Users collection.
users: [
{ _id: ObjectId('1...'), username: 'jack' },
{ _id: ObjectId('2...'), username: 'john' },
{ _id: ObjectId('3...'), username: 'james' }
]
Tasks collection.
tasks: [
{ _id: ObjectId('...'), userId: '1...', taskName: 'task 1' },
{ _id: ObjectId('...'), userId: '1...', taskName: 'task 2' },
{ _id: ObjectId('...'), userId: '1...', taskName: 'task 3' },
{ _id: ObjectId('...'), userId: '2...', taskName: 'task 1' },
{ _id: ObjectId('...'), userId: '3...', taskName: 'task 1' },
{ _id: ObjectId('...'), userId: '3...', taskName: 'task 2' }
]
This is where I came so far.
UsersModel.aggregate([
{
$lookup: {
from: 'tasks',
localField: '_id',
foreignField: 'userId',
as: 'tasks'
}
},
{
$group: {
_id: '$_id',
totalTasks: { $sum: '$tasks.userId' }
}
},
{
$sort: { totalTasks: -1 }
}
], (err, res) => {
if (err) console.log(err)
console.log(res)
})
But I'm getting results like this.
[
{ _id: 1..., totalTasks: 0 },
{ _id: 2..., totalTasks: 0 },
{ _id: 3..., totalTasks: 0 }
]
But this is what I'm looking for.
[
{ _id: 1..., totalTasks: 3 },
{ _id: 3..., totalTasks: 2 },
{ _id: 2..., totalTasks: 1 }
]
I'm not sure this is the problem but the type of users._id
is ObjectId
and the type of tasks.userId
is String
. I'm stuck and need some help.