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
Release: 2024-11-07 08:01:02
Original
1070 people have browsed it

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!

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