MongoDB Aggregate Sorting
To perform aggregation operations with MongoDB, you need to have a good understanding of the aggregation pipeline stages. This tutorial will explore $sort
the stages through an example to perform a MongoDB aggregation sort.
MongoDB Aggregate Sorting
Let's have a scenario to practice the code examples. We have a student
collection called which contains basic information.
You can also use the following query to be on the same page with us.
Sample code:
> db.createCollection('student');
> db.student.insertMany([
{"student_code": "ma001", "name": "Mehvish Ashiq", "postcode": 2000},
{"student_code": "tc002", "name": "Thomas Christopher", "postcode": 2001},
{"student_code": "km003", "name": "Krishna Mehta", "postcode": 2000},
{"student_code": "ar004", "name": "Aftab Raza", "postcode": 2000},
{"student_code": "za005", "name": "Zeenat Ashraf", "postcode": 2002},
{"student_code": "ka006", "name": "Kanwal Ali", "postcode": 2002}
]);
> db.student.find().pretty();
Output:
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e97b"),
"student_code" : "ma001",
"name" : "Mehvish Ashiq",
"postcode" : 2000
}
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e97c"),
"student_code" : "tc002",
"name" : "Thomas Christopher",
"postcode" : 2001
}
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e97d"),
"student_code" : "km003",
"name" : "Krishna Mehta",
"postcode" : 2000
}
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e97e"),
"student_code" : "ar004",
"name" : "Aftab Raza",
"postcode" : 2000
}
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e97f"),
"student_code" : "za005",
"name" : "Zeenat Ashraf",
"postcode" : 2002
}
{
"_id" : ObjectId("629afe5a0a3b0e96fe92e980"),
"student_code" : "ka006",
"name" : "Kanwal Ali",
"postcode" : 2002
}
Next, we want to determine the class that holds the maximum number of students but in a sorted form postcode
. To do this, check the following sample code.
Sample code:
> db.student.aggregate([
{ $group: { _id: '$postcode', students: { $sum: 1 } } },
{ $sort: {_id: 1} }
]);
Output:
{ "_id" : 2000, "students" : 3 }
{ "_id" : 2001, "students" : 1 }
{ "_id" : 2002, "students" : 2 }
Here, we use aggregate()
the function to calculate the aggregate value of the data in the specified collection or view . In aggregate()
the method, we postcode
group the documents based on the field.
Furthermore, we postcode
return as _id
, where students are postcode
counted for each students
. Here, we use $sum
to get postcode
the number of students for each .
$sum
Computes and returns the sum of numeric values by ignoring non-numeric values.
Finally, we use $sort
phase to sort them in ascending or descending order based on the project needs. 1
is used for ascending order, while -1
is used for descending order.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
List all collections in MongoDB Shell
Publish Date:2025/04/29 Views:156 Category:MongoDB
-
When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c
Querying for non-null values in MongoDB
Publish Date:2025/04/29 Views:139 Category:MongoDB
-
This MongoDB article will explain how to query for non-null values in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers
Shutting down with code:100 error in MongoDB
Publish Date:2025/04/29 Views:53 Category:MongoDB
-
This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know
SELECT COUNT GROUP BY in MongoDB
Publish Date:2025/04/29 Views:74 Category:MongoDB
-
In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation
Differences between MongoDB and Mongoose
Publish Date:2025/04/29 Views:80 Category:MongoDB
-
This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s
Install MongoDB using Homebrew
Publish Date:2025/04/29 Views:161 Category:MongoDB
-
MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a
Create a MongoDB dump of the database
Publish Date:2025/04/29 Views:62 Category:MongoDB
-
In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t
Get the size of the database in MongoDB
Publish Date:2025/04/29 Views:88 Category:MongoDB
-
When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;
Grouping values by multiple fields with MongoDB
Publish Date:2025/04/29 Views:99 Category:MongoDB
-
MongoDB Group by Multiple Fields is used to group values by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per