Home > Web Front-end > JS Tutorial > How to Sort Embedded Arrays in MongoDB Collections?

How to Sort Embedded Arrays in MongoDB Collections?

Patricia Arquette
Release: 2024-11-07 07:27:03
Original
291 people have browsed it

How to Sort Embedded Arrays in MongoDB Collections?

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

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

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!

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