Sorting Embedded Arrays in MongoDB Collections
Problem:
You have a MongoDB collection of student records, each containing an embedded array of scores. You wish to sort the scores array in descending order of score for a specific document.
Solution:
To sort an embedded array, you can utilize either custom application code or the Aggregation Framework introduced in MongoDB 2.2.
Using Aggregation Framework:
The following MongoDB shell aggregation pipeline sorts the scores array of the document with _id 1 in descending order of score:
db.students.aggregate( { $match: { _id : 1 }}, { $unwind: '$scores' }, { $match: { 'scores.type': 'homework' }}, { $sort: { 'scores.score': -1 }} )
Output:
This aggregation produces the following output, showing the sorted homework scores for the student with _id 1:
{ "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 }
The above is the detailed content of How to Sort Embedded Arrays in MongoDB Collections?. For more information, please follow other related articles on the PHP Chinese website!