在MongoDB中对子文档数组进行排序

时间:2018-10-26 01:00:17

标签: mongodb sorting

所以我的数据库中有此商店集合,商店文档具有以下格式:

{
    "_id" : ObjectId("5bb221faf4f7171bc008d76a"),
    "name" : "Kwkik-E Market",
    "products" : [ 
        {
            "_id" : ObjectId("5bb58e6285f54d1b38e3ff73"),
            "title" : "KKCK",
            "typeOfItem" : "alcohol",
            "sellingPrice" : 5.75,
        }, 
        {
            "verified" : true,
            "_id" : ObjectId("5bb79d4ac24fdd2298ffd530"),
            "title" : "Vino Tindo D.O. Canarias",
            "sellingPrice" : 23,
        }, 
        {
            "_id" : ObjectId("5bbbd28dd186de13044e6137"),
            "title" : "Test",
            "typeOfItem" : "alcohol",
            "sellingPrice" : 17.25,
        },
}

我如何返回相同的文档,但将其产品系列按其SellingPrice排序?将新的子文档推送到数组时,对子文档进行排序是否更好?

非常感谢

1 个答案:

答案 0 :(得分:0)

这应该可以满足您的需求

db.yourcollectionhere.aggregate([
    {
        $unwind: '$products'
    },
    {
        $sort: {
           products: 1
        }
    },
    {
        $group: {
            _id: {
                _id: '$_id',
                name: '$name'
            },
            products: {$push: '$products'}
        }
    },
    {
        $project: {
            _id: '$_id._id',
            name: '$_id.name',
            products: '$products'
        }
    }
])

我希望这会有所帮助!