Sorting Array within a Collection Record in MongoDB
Problem Statement
Consider a collection of student records in MongoDB, where each record includes an embedded array of scores. The task is to sort the scores array in descending order based on the score value.
Solution
Due to the limitations of MongoDB's query language, directly manipulating the embedded array within the query itself is not possible. To achieve this sorting, you can explore two approaches:
1. Application-Level Sorting
Extract the scores array from the collection using a find query. Sort the scores array in descending order within your application code. Update the record with the sorted scores array back into MongoDB.
2. MongoDB Aggregation Framework
Utilizing the MongoDB Aggregation Framework, you can perform the sorting within MongoDB itself. Here's a sample aggregation pipeline that sorts homework scores in descending order:
db.students.aggregate([ { $match: { _id: 1 } }, // Initial document match { $unwind: '$scores' }, // Expand scores array into individual documents { $match: { 'scores.type': 'homework' } }, // Filter to homework scores { $sort: { 'scores.score': -1 } }, // Sort in descending order ])
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 }
The above is the detailed content of How to Sort an Embedded Array of Scores in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!