Sorting Nested Arrays in MongoDB
Problem:
How do you sort an embedded array field in a MongoDB document, such as the scores array in the student collection?
Proposed Solution:
Due to limitations in Mongo's native sorting capabilities, you need to use either application code or MongoDB Aggregation Framework to manipulate embedded arrays.
Aggregation Framework Solution:
Using the MongoDB Aggregation Framework, you can perform the following steps to sort the scores array in descending order:
Aggregation Example:
db.students.aggregate([ // Initial document match { $match: { _id : 1 }}, // Expand scores array { $unwind: '$scores' }, // Filter homework scores { $match: { 'scores.type': 'homework' }}, // Sort in descending order { $sort: { 'scores.score': -1 }} ])
Output (Sample):
{ "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 an Embedded Array Field in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!