MongoDB aggregation sort not working

前端 未结 2 1485
一生所求
一生所求 2021-02-13 03:44

I\'m having a problem applying a sort to an aggregation grouping. My raw data looks like the following:

    {
            \"_id\" : ObjectId(\"52deab2fe4b0a491         


        
相关标签:
2条回答
  • 2021-02-13 03:59

    so here is the issue come sorting over the Aggregation result.

    Here the field which you are sorting is the part of the ID, so basically your aggregation operation is performing the average operation and returning the result sets with 2 Fileds called "_id" and "buildDuration" , since you are doing sorting over the inner field of "_id", you have to define Sort attributes in following Way.

    { $sort: {
            '_id.buildProjectName': 1, 
            '_id.year': 1, 
            '_id.month': 1, 
            '_id.day': 1
        } }
    

    Hopefully, this will help you. Contact me if you have any doubt.

    0 讨论(0)
  • 2021-02-13 04:25

    The fields you're sorting on are part of the _id so you need to include that in your $sort field names:

    db.builds.aggregate([
        { $group: { 
            _id: { 
                month: { $month: "$time" },
                day: { $dayOfYear: "$time" },
                year: { $year: "$time" }, 
                buildProjectName: "$data.buildProjectName", 
            },
            buildDuration: { $avg: "$data.buildDuration" } 
        } },
        { $sort: {
            '_id.buildProjectName': 1, 
            '_id.year': 1, 
            '_id.month': 1, 
            '_id.day': 1
        } }
    ])
    
    0 讨论(0)
提交回复
热议问题