Home > Back-end >  MongoDB $lookup and $group returns empty Array
MongoDB $lookup and $group returns empty Array

Time:09-23

I am trying to use the following aggregation:

[
    {$unwind: '$names'},
    {$sort: {'names.changed_at': -1}},
    {$group: {_id: '$_id', names: {$push: {value: '$names.value', changed_at: '$names.changed_at'}}}},
    {$limit: 3},
    {
        $lookup: {
            from: 'users',
            localField: 'id',
            foreignField: 'id',
            as: 'user',
        },
    },
    {$unwind: '$user'},
    {
        $project: {
            _id: 0,
            old_name: {$first: '$names'},
            user: {avatar_url: 1, current_tag: 1},
        },
    }
]

With $lookup and $group it returns []. When I remove either $lookup or $group it works and gives the expected result.

How do I fix this?

CodePudding user response:

You're trying to use the id field for the $lookup but after this $group stage:

{ $group: { _id: '$_id', names: { $push: { value: '$names.value', changed_at: '$names.changed_at' } } } },

The document structure is:

{
  _id: ObjectId,
  names: { value: string, changed_at: Date }[]
}

As you can see, there is no id field.

If this is a typo just change id to _id. if this is not a typo then you need to "save" the id field in the $group stage, like so:

{
    $group: {
        _id: '$_id',
        names: {$push: {value: '$names.value', changed_at: '$names.changed_at'}},
        id: {$first: "$id"}
    }
}
  • Related