首页  >  问答  >  正文

使用聚合查询后对组集合进行排序

我使用聚合来让所有用户具有相同的名称,但是每当我查询此 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();

记录的顺序未排序

P粉558478150P粉558478150258 天前322

全部回复(1)我来回复

  • P粉739942405

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

    你必须不敏感地对 case 进行排序
    假设您需要 nameage

    尝试这个查询:

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

    回复
    0
  • 取消回复