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

How to Sort Arrays within Embedded Documents in MongoDB?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 08:01:021049browse

How to Sort Arrays within Embedded Documents in MongoDB?

Sorting Arrays within Embedded Documents in MongoDB

When working with MongoDB, it is often necessary to sort arrays contained within embedded documents. This can be a tricky task, but fortunately there are several methods available.

This question revolves around sorting the "scores" array within the student records in descending order of score. The proposed solution relies on using the mongo shell and the Aggregation Framework, a new feature introduced in MongoDB 2.2.

The aggregation query provided in the answer employs several stages:

  1. $match: This stage filters the collection for the desired document using a match criterion. In this case, it selects the document with _id equal to 1.
  2. $unwind: This stage deconstructs the embedded "scores" array, transforming it into a stream of individual documents. Each document contains the student's _id, name, and a single score.
  3. $match: This stage filters the unwound documents based on the "type" field, selecting only those with "type" equal to "homework".
  4. $sort: This stage sorts the documents in descending order of the "score" field within the "scores" embedded document.

The result is a set of documents with the _id, name, and highest homework score for each student. It is important to note that the Aggregation Framework allows for more complex transformations and filtering, making it a powerful tool for working with embedded arrays in MongoDB.

The above is the detailed content of How to Sort Arrays within Embedded Documents 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