SELECT COUNT GROUP BY in 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.
Operations in MongoDB
The user interface principles that allow users to browse, search, and change database elements are called CRUD operations.
Connecting to the server, querying for the corresponding documents, making modifications before sending the data back to the database for processing, and changing settings properties are how you modify MongoDB documents.
CRUD is a data-driven process that is standardized using HTTP action verbs. Following are the CRUD operations and their uses.
Aggregation Operations
It is a data processing operation that consists of multiple stages that perform multiple operations on grouped data to provide a single output. Given below are the three ways to perform aggregation operation:
Aggregation pipeline
Documents are fed into a multi-stage pipeline that combines them into a single output. The MongoDB aggregation process has several stages.
example:
db.collection_name.aggregate([
//First stage
{ $match: { status: "" } },
//Second stage
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
//Third Stage
{ $sort : {sort_field: -1 }}
])
Single-Purpose Aggregation Method
Single-purpose aggregation methods are simple but lack the power of aggregation pipelines.
Map-Reduce Process
Starting in MongoDB 5.0, the map-reduce process is deprecated. Use the aggregation pipeline instead.
MongoDB GROUP BY
andCOUNT
The fields of each document in MongoDB _id
have been assigned a unique group by value. The data is then processed by the aggregation process to provide the calculated results.
An example is given below. Here you can see the configuration of the database.
This configuration will be used in all code examples provided in this article.
db={
"data": [
{
"_id": ObjectId("611a99100a3322fc1bd8c38b"),
"fname": "Tom",
"city": "United States of America",
"courses": [
"c#",
"asp",
"node"
]
},
{
"_id": ObjectId("611a99340a3322fc1bd8c38c"),
"fname": "Harry",
"city": "Canada",
"courses": [
"python",
"asp",
"node"
]
},
{
"_id": ObjectId("611a99510a3322fc1bd8c38d"),
"fname": "Mikky",
"city": "New Zealand",
"courses": [
"python",
"asp",
"c++"
]
},
{
"_id": ObjectId("611b3e88a60b5002406571c3"),
"fname": "Ron",
"city": "United Kingdom",
"courses": [
"python",
"django",
"node"
]
}
]
}
The query used for the above database is:
db.data.aggregate([
{
$group: {
_id: "ObjectId",
count: {
$count: {}
}
}
}
])
MongoDB GROUP BY
,COUNT
SORT
$sortByCount
Used by the count sorting theme in this group, it is $group
the same as , plus $sort.
. It can be used to sort and count a group in ascending and descending order.
In the following example, some documents are added to the dataset. find()
The function is used to see how many records it has.
find()
The query would be:
db.data.find()
The next step is to 展开``courses
add the array and use $sortByCount
the function to count the number of documents added to each course. The query for this step is:
db.data.aggregate([
{
$unwind: "$courses"
},
{
$sortByCount: "$courses"
}
])
This is the most straightforward way for MongoDB to group, count, and sort arrays.
MongoDB GROUP BY
and COUNT
multiple fields
You can make use of the method in MongoDB aggregate()
to count many fields. Hence, $count
is used to count the fields.
An example is given below where the timestamp is used for only one entry. In this example, a number of papers could be stored in student
a collection and you could use find()
the function to determine how many documents you have.
db.student.aggregate([ {$group: {_id: {name:"$name",
timestamp:"$timestamp" }}},
{$count:"timestamp"}
])
MongoDB GROUP BY
Date andCOUNT
When you want to count documents for a specific date, you can use the count aggregation and count documents for a specific date.
In the following example, you will learn to calculate the total sales and sales for each day in 2021.
You can add fields product_id, item_name, price, quantity, and date to the sales collection. find()
The function can get the document.
db=
{
"_id" : 1,
"item" : "abc",
"price" : NumberDecimal("10"),
"quantity" : 2,
"date" : ISODate("2021-03-01T08:00:00Z")
}
{
"_id" : 2,
"item" : "jkl",
"price" : NumberDecimal("20"),
"quantity" : 1,
"date" : ISODate("2021-03-01T09:00:00Z")
}
{
"_id" : 3,
"item" : "xyz",
"price" : NumberDecimal("5"),
"quantity" : 10,
"date" : ISODate("2021-03-15T09:00:00Z")
}
{
"_id" : 4,
"item" : "xyz",
"price" : NumberDecimal("5"),
"quantity" : 20,
"date" : ISODate("2021-04-04T11:21:39.736Z")
}
{
"_id" : 5,
"item" : "abc",
"price" : NumberDecimal("10"),
"quantity" : 10,
"date" : ISODate("2021-04-04T21:23:13.331Z")
}
The query for the above configuration would be:
db.date.aggregate([
{
$match : { "date": { $gte: new ISODate("2021-01-01"), $lt: new ISODate("2015-01-01") } }
},
{
$group : {
_id : { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
count: { $sum: 1 }
}
},
{
$sort : { totalSaleAmount: -1 }
}
])
Now COUNT
give below the queries for single field group and multiple field groups using and FIELD commands.
MongoDB with a single field GROUP BY
andCOUNT
db.Request.aggregate([
{"$group" : {_id:"$source", count:{$sum:1}}}
])
MongoDB with multiple fields GROUP BY
andCOUNT
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
])
MongoDB GROUP BY
and COUNT
sorting using a field with multiple fields
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
{$sort:{"_id.source":1}}
])
MongoDB GROUP BY
and COUNT
sorting using multiple fields
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
{$sort:{"count":-1}}
])
This article discusses operations in detail and also discusses aggregation operations. First, different types of aggregation functions are briefly discussed with code snippets.
Then we discuss GROUP BY
and COUNT
, including sorting, searching, and multiple fields. Then we discuss and using the field and count
commands .GROUP BY
COUNT
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
Use find operator to join multiple conditions in MongoDB
Publish Date:2025/04/29 Views:132 Category:MongoDB
-
$lookup Today, we will see how to concatenate multiple conditions using the operator in MongoDB . In addition, we will explore some examples to demonstrate the use of $group the stage and $unionWidth the aggregation stage. $lookup Use the o
Date comparison in MongoDB
Publish Date:2025/04/28 Views:170 Category:MongoDB
-
This MongoDB tutorial discusses the issue of returning Date-based queries. In addition, there is also a good tutorial on how to use Date Range queries in MongoDB. Using date ranges in MongoDB We will learn to write MongoDB date range querie
Find objects between two dates in MongoDB
Publish Date:2025/04/28 Views:95 Category:MongoDB
-
In this article, the problem of finding objects between two dates was briefly discussed. In addition, the operators $gte, $lte, $gt, and $lt used for this purpose were briefly explained in detail. Querying date ranges in MongoDB This sectio
Comparing Dates in MongoDB
Publish Date:2025/04/28 Views:115 Category:MongoDB
-
Date is a common field in most databases, and sometimes we need to find exact documents from a collection in MongoDB. For example, if we have a collection of orders, we might search for those documents before or after a specific date. In th
Convert string to date in MongoDB
Publish Date:2025/04/28 Views:162 Category:MongoDB
-
MongoDB is an excellent platform that is growing in popularity. Among the various features it offers, MongoDB also allows you to convert data from one type to another. This may seem like a complex function, but it is very simple to execute.
Building the MongoDB REST API
Publish Date:2025/04/28 Views:71 Category:MongoDB
-
MongoDB is a flexible and scalable document-oriented database system that is widely used for large-volume data storage. It uses documents and collections instead of the traditional rational database approach of using tables and rows. MongoD