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

How to Sort Embedded Arrays in MongoDB in Descending Order?

Susan Sarandon
Release: 2024-11-10 03:12:02
Original
744 people have browsed it

How to Sort Embedded Arrays in MongoDB in Descending Order?

Sorting Embedded Array in MongoDB

Question:

How can I sort the scores array within each student record in a MongoDB collection in descending order of score?

Problem:

Consider the following student record:

{
  "_id": 1,
  "name": "Aurelia Menendez",
  "scores": [
    {
      "type": "exam",
      "score": 60.06045071030959
    },
    {
      "type": "quiz",
      "score": 52.79790691903873
    },
    {
      "type": "homework",
      "score": 71.76133439165544
    },
    {
      "type": "homework",
      "score": 34.85718117893772
    }
  ]
}
Copy after login

An attempt to manually iterate over the scores array using embedded JavaScript in the mongo shell prompts an error.

Solution:

To sort the scores array, consider the following MongoDB Aggregation Framework pipeline:

db.students.aggregate(
  // Match the document (uses index if suitable)
  { $match: {
      _id: 1
  }},
  // Unwind scores array
  { $unwind: '$scores' },
  // Filter to specific score type (optional)
  { $match: {
      'scores.type': 'homework'
  }},
  // Sort scores array
  { $sort: {
      'scores.score': -1
  }}
)
Copy after login

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

The above is the detailed content of How to Sort Embedded Arrays in MongoDB in Descending Order?. 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