Mongoose Aggregate with Lookup

I have simple two collections as shown below:

tasks:

[
    {
        "_id": "593eff62630a1c35781fa325",
        "topic_id": 301,
        "user_id": "59385ef6d2d80c00d9bdef97"
    },
    {
        "_id": "593eff62630a1c35781fa326",
        "topic_id": 301,
        "user_id": "59385ef6d2d80c00d9bdef97"
    }
]

      

and collecting users:

[   
    {
        "_id": "59385ef6d2d80c00d9bdef97",
        "name": "XX"
    },
    {
        "_id": "59385b547e8918009444a3ac",
        "name": "YY"
    }
]

      

and my intention is to aggregate user_id request when assembling assignments, and also I would like to include user.name in this group collection. I tried below:

Assignment.aggregate([{
                $match: {
                    "topic_id": "301"
                }
            },
            {
                $group: {
                    _id: "$user_id",
                    count: {
                        $sum: 1
                    }
                }
            },
            {
                $lookup: {
                    "from": "kullanicilar",
                    "localField": "user_id",
                    "foreignField": "_id",
                    "as": "user"
                }
            },
            {
                $project: {
                    "user": "$user",
                    "count": "$count",
                    "_id": "$_id"
                }
            },

      

But the problem is that the custom array is always empty.

[ { _id: '59385ef6d2d80c00d9bdef97', count: 1000, user: [] } ]

      

I need something like:

[ { _id: '59385ef6d2d80c00d9bdef97', count: 1000, user: [_id:"59385ef6d2d80c00d9bdef97",name:"XX"] } ]

      

+3


source to share





All Articles