How to sort array inside collection record in MongoDB? How to sort array inside collection record in MongoDB? mongodb mongodb

How to sort array inside collection record in MongoDB?


You will need to manipulate the embedded array in your application code or using the new Aggregation Framework in MongoDB 2.2.

Example aggregation in the mongo shell:

db.students.aggregate(    // Initial document match (uses index, if a suitable one is available)    { $match: {        _id : 1    }},    // Expand the scores array into a stream of documents    { $unwind: '$scores' },    // Filter to 'homework' scores     { $match: {        'scores.type': 'homework'    }},    // Sort in descending order    { $sort: {        'scores.score': -1    }})

Sample output:

{    "result" : [        {            "_id" : 1,            "name" : "Aurelia Menendez",            "scores" : {                "type" : "homework",                "score" : 71.76133439165544            }        },        {            "_id" : 1,            "name" : "Aurelia Menendez",            "scores" : {                "type" : "homework",                "score" : 34.85718117893772            }        }    ],    "ok" : 1}


Since this question can be managed in different ways i want to say that another solution is "insert and sort", in this way you will get the Ordered array at the moment you will made a Find().

Consider this data:

{   "_id" : 5,   "quizzes" : [      { "wk": 1, "score" : 10 },      { "wk": 2, "score" : 8 },      { "wk": 3, "score" : 5 },      { "wk": 4, "score" : 6 }   ]}

Here we will update the Document, make the Sort.

db.students.update(   { _id: 5 },   {     $push: {       quizzes: {          $each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],          $sort: { score: -1 },          $slice: 3 // keep the first 3 values       }     }   })

Result is:

{  "_id" : 5,  "quizzes" : [     { "wk" : 1, "score" : 10 },     { "wk" : 2, "score" : 8 },     { "wk" : 5, "score" : 8 }  ]}

Documentation:https://docs.mongodb.com/manual/reference/operator/update/sort/#up._S_sort


That's how we could solve this with JS and mongo console:

db.students.find({"scores.type": "homework"}).forEach(  function(s){    var sortedScores = s.scores.sort(      function(a, b){        return a.score<b.score && a.type=="homework";      }    );    var lowestHomeworkScore = sortedScores[sortedScores.length-1].score;    db.students.update({_id: s._id},{$pull: {scores: {score: lowestHomeworkScore}}}, {multi: true});  })