Home  >  Q&A  >  body text

Sort group collection after using aggregate query

I'm using aggregation to have all users with the same name, but whenever I query this API, the results returned are not sorted even if I add the $sort by 'name' field.

const aggregateQuery: any = [
            { $group: { _id: '$name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } },
            { $match: { count: { $gt: 1 } } },
            { $unwind: '$users' },
            { $replaceRoot: { newRoot: '$users' } },
            { $sort: { name: 1 } }
        ];`

        const users = await this.userRepository.getModel().aggregate(aggregateQuery).exec();

The order of records is not sorted

P粉558478150P粉558478150258 days ago326

reply all(1)I'll reply

  • P粉739942405

    P粉7399424052024-02-05 00:05:39

    You must sort cases insensitively
    Assuming you need name and age,

    Try this query:

    [ { "$project": { "name": 1, "age" : 1, "insensitive": { "$toLower": "$name" } }},{ $group: { _id : ' $name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } }, { $match: { count: { $gte: 1 } } }, { $unwind: '$users' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { insensitive: 1 } } ]

    If you have more fields to add to the output, try the following query instead of the one above.

    [ { "$project": { "name": 1, createdAt : 1 }},{ $group: { _id: '$name', count: { $sum: 1 }, users: { $push : '$$ROOT' } } }, { $match: { count: { $gte: 1 } } }, {"$addFields":{"users.insensitive": { "$toLower": "$_id " } ,}}, { $unwind: '$users' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { insensitive: 1 } } ]

    reply
    0
  • Cancelreply