Aggregate two collection & find all datafrom the first one

Hello,

I don’t know how to aggregate to have the actual result for my two collection

Example my first one is : Task

[{
    "_id": {
        "$oid": "id...."
    },
    "codeex": "...example",
    "one": "testexample",
    "two": "testexample",
    }
},{
    "_id": {
        "$oid": "id...."
    },
    "codeex": "...example",
    "one": "testexample",
    "two": "testexample",
    }
}]

Example 2 : Users

{
    "_id": {
        "$oid": "id...."
    },
    "task: { 
         id: "...task.id",
        name: 'err',
}
 }
{
    "_id": {
        "$oid": "id...."
    },
    "task: { 
         id: "...task.id",
        name: 'err',
}
 }

The attended result is like a find { } with a projection of all the field of the Tasks in an array for each tasks but with a new value by tasks countUser: wich will be the number of the user who have the task id linked

Thanks i know how to use a little bit aggregate etc… but actually i don’t get the right result

  .aggregate(
    {
      $lookup: {
        from: 'users',
        localField: '_id',
        foreignField: 'tasks.id',
        as: 'user',
      },
    },
    { $unwind: '$user' },
    {
      $group: {
        _id: '$user._id',
        count: { $sum: 1 },
      },
    },
    {
      $group: {
        _id: null,
        total: { $sum: '$count' },
      },
    },
  ).toArray();

This is my first reflexion thanks

You can get the number of users by project the size of the array you got after lookup


    [{
    $lookup: {
      from: 'users',
      localField: '_id',
      foreignField: 'task.id',
      as: 'users'
    }}, 
    {$set: {
      usersCount: {$size: "$users"}
    }}, 
    {$project: {
      users:0
    }}]

I didn’t quite get how do you want the array for each talk to look like, maybe $objectToArray can help