Sorting Embedded Array in MongoDB
Question:
How can I sort the scores array within each student record in a MongoDB collection in descending order of score?
Problem:
Consider the following student record:
{ "_id": 1, "name": "Aurelia Menendez", "scores": [ { "type": "exam", "score": 60.06045071030959 }, { "type": "quiz", "score": 52.79790691903873 }, { "type": "homework", "score": 71.76133439165544 }, { "type": "homework", "score": 34.85718117893772 } ] }
An attempt to manually iterate over the scores array using embedded JavaScript in the mongo shell prompts an error.
Solution:
To sort the scores array, consider the following MongoDB Aggregation Framework pipeline:
db.students.aggregate( // Match the document (uses index if suitable) { $match: { _id: 1 }}, // Unwind scores array { $unwind: '$scores' }, // Filter to specific score type (optional) { $match: { 'scores.type': 'homework' }}, // Sort scores array { $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 Embedded Arrays in MongoDB in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!