Home > Web Front-end > JS Tutorial > body text

How to Sort an Embedded Array of Scores in MongoDB?

Barbara Streisand
Release: 2024-11-06 22:29:02
Original
623 people have browsed it

How to Sort an Embedded Array of Scores in MongoDB?

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
])
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!