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
You must sort
cases insensitively
Assuming you need
name
andage
,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 } } ]