英文:
Sorting group collection after query with aggregate
问题
我使用聚合操作来获取所有具有相同名称的用户,但无论我如何查询此API,返回的结果都没有排序,即使我通过'$sort'字段进行了排序。
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();
记录的顺序没有排序。
英文:
I use aggregate to get all users have same name, but whenever I query to this API, the results return are not sorted even thought I add $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 the records is not sorted
答案1
得分: 0
你需要进行不区分大小写
的排序。如果需要name
和age
,可以尝试以下查询:
[
{ "$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 } }
]
如果需要将更多字段添加到输出中,可以尝试以下查询:
[
{ "$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 } }
]
英文:
you have to sort case insensitively
Let's say 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 be added to the output, then instead of the above query, try the below one.
[ { "$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 } } ]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论