我使用聚合来让所有用户具有相同的名称,但是每当我查询此 API 时,即使我添加 $sort by 'name' 字段,返回的结果也不会排序。
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();
记录的顺序未排序
你必须不敏感地对
case 进行排序
假设您需要
name
和age
,尝试这个查询:
[ { "$project": { "name": 1, "age" : 1, "insensitive": { "$toLower": "$name" } }},{ $group: { _id: ' $name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } }, { $match: { count: { $gte: 1 } } }, { $unwind: '$用户' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { insensitive: 1 } } ]
如果您有更多字段要添加到输出中,请尝试以下查询,而不是上面的查询。
[ { "$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 } } ]