如何在 mongodb 中根据嵌套子对象键对集合进行排序? [关闭]

问题描述 投票:0回答:0

我在 mongodb 中有 json 文档 as

{
    "_id" : ObjectId("643e62fb6cb4524dd444df0f"),
    "invoiceDetails" : {
        "amount" : 123.14,
        "balance" : 123.14,
        "contactName" : "Diego",
        "currency" : "$",
        "date" : "2022-08-29",
        "dueDate" : "2022-09-28",
        "id" : "151",
        "platformId" : "151",
        "refNumber" : "1043"
    },
    "payeeBankAccount" : {
        "bankAccountId" : "g4NA5J6vrvIGkLPe74EjHXVp9n",
        "orumAccountReferenceId" : "5b56bcc7-30e1-48d3-96b2",
        "accountMask" : "******0000"
    },
    "payeeId" : ObjectId("643e614d396c01623c41864c"),
    "payerId" : ObjectId("643e5ced396c01623c41861b"),
    "status" : "PENDING"
}

我正在对其应用聚合以过滤掉数据,并希望根据

invoiceDetails
下的键应用排序。

db.getCollection('payments').aggregate({$match: { status: 'PENDING',payerId: ObjectId("643e5ced396c01623c41861b") }}  , 
     { $lookup: {
                    from: "businesses",
                    localField: 'payeeId',
                    foreignField: '_id',
                    as: 'businessDetails',
                    pipeline: [ {$project: {businessName: 1, businessEmail: 1} } ],

                } 
                }
    
,
{ $unset: "payeeBankAccount" },
{$sort: {"$invoiceDetails.date":-1}})

聚合后的数据

{
    "_id" : ObjectId("643e62fb6cb4524dd444df0f"),
    "invoiceDetails" : {
        "amount" : 123.14,
        "balance" : 123.14,
        "contactName" : "Diego Rodriguez",
        "currency" : "$",
        "date" : "2022-08-29",
        "dueDate" : "2022-09-28",
        "id" : "151",
        "platformId" : "151",
        "refNumber" : "1043"
    },
    "payeeId" : ObjectId("643e614d396c01623c41864c"),
    "payerId" : ObjectId("643e5ced396c01623c41861b"),
    "status" : "PENDING",
    "businessDetails" : [ 
        {
            "_id" : ObjectId("643e614d396c01623c41864c"),
            "businessName" : "Development2",
            "businessEmail" : "[email protected]"
        }
    ]
}

但是我无法对集合中的文档进行排序。请告诉我我怎样才能做到这一点?

node.js mongodb mongoose mongodb-query aggregate
© www.soinside.com 2019 - 2024. All rights reserved.