对查询进行聚合后,对分组集合进行排序

huangapple go评论65阅读模式
英文:

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

你需要进行不区分大小写的排序。如果需要nameage,可以尝试以下查询:

[ 
  { "$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 } } ]

huangapple
  • 本文由 发表于 2023年5月17日 14:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定