Home >Web Front-end >JS Tutorial >How to Sort an Embedded Array Field in MongoDB?

How to Sort an Embedded Array Field in MongoDB?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 22:54:03656browse

How to Sort an Embedded Array Field in MongoDB?

Sorting Nested Arrays in MongoDB

Problem:
How do you sort an embedded array field in a MongoDB document, such as the scores array in the student collection?

Proposed Solution:
Due to limitations in Mongo's native sorting capabilities, you need to use either application code or MongoDB Aggregation Framework to manipulate embedded arrays.

Aggregation Framework Solution:
Using the MongoDB Aggregation Framework, you can perform the following steps to sort the scores array in descending order:

  1. Document Match: Match the desired document using a suitable index, if available.
  2. Array Expansion: Unwind the scores array to create a stream of documents for each score.
  3. Type Filtering: Filter the stream to select scores of a specific type (e.g., 'homework').
  4. Sorting: Sort the scores in descending order.

Aggregation Example:

db.students.aggregate([
    // Initial document match
    { $match: {
        _id : 1
    }},
    // Expand scores array
    { $unwind: '$scores' },
    // Filter homework scores
    { $match: {
        'scores.type': 'homework'
    }},
    // Sort in descending order
    { $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 an Embedded Array Field in MongoDB?. 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