首頁  >  問答  >  主體

使用聚合查詢後對群組集合進行排序

我使用聚合來讓所有使用者俱有相同的名稱,但是每當我查詢此 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 天前325

全部回覆(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
  • 取消回覆