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

How to Sort Embedded Arrays in MongoDB Collections?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 07:27:03290browse

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
    }}
)

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
}

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!

Statement:
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