MongoDB Aggregate and Group Document

Introduction

If you’ve been working with data in MongoDB, you probably already know that you can have the results of a query sorted in a particular order. However, you might not have realized that you can also aggregate documents and group them based on a common value for a field. Using these groupings can make your results easier to read and understand, allowing you to gain deeper insights into your data. In this article, we’ll show you how to use MongoDB to aggregate and group documents.

Prerequisite

Before proceeding with the steps in this tutorial, make sure that MongoDB server is installed and properly configured on your machine.

MongoDB Sample Document

We’re going to need a MongoDB sample document that we can use for our tutorial, so let’s create that first. We’ll follow these steps in order:

  1. First, log in to our MongoDB shell.
  2. Then, we’ll create a database named housedb.
  3. Finally, we’ll create a collection named house and insert some documents into it.

Here’s how we accomplish these steps:

> use housedb
switched to db housedb
> db.house.insertMany( [
...
... { _id : "1001", name: "Camelia", level: 1, bedrooms: 3, Builder : "DMCI" },
... { _id : "1002", name: "Nora", level: 2, bedrooms: 5, Builder : "JAP" },
... { _id : "1003", name: "Rose", level: 1, bedrooms: 2, Builder : "SUMICON" },
... { _id : "1004", name: "Nico", level: 1, bedrooms: 2, Builder : "JAP" },
... { _id : "1005", name: "Estrada", level: 2, bedrooms: 6, Builder : "DMCI" },
... { _id : "1006", name: "Abishai", level: 2, bedrooms: 6, Builder : "SUMICON" },
... { _id : "1007", name: "Erma", level: 2, bedrooms: 5, Builder : "DMCI" },
... { _id : "1008", name: "Dex", level: 2, bedrooms: 5, Builder : "DMCI" },
... { _id : "1009", name: "Lava", level: 1, bedrooms: 3, Builder : "JAP" },
... { _id : "1010", name: "PLUMA", level: 2, bedrooms: 5, Builder : "SUMICON" },
...
...
... ] );

We’ll receive a notification from the Mongo shell that looks something like the following:

{
        "acknowledged" : true,
        "insertedIds" : [
                "1001",
                "1002",
                "1003",
                "1004",
                "1005",
                "1006",
                "1007",
                "1008",
                "1009",
                "1010"
        ]
}

If you’d like to confirm that your insert operation was successful, use the following command: db.house.find()

The output should look like this:

> db.house.find()
{ "_id" : "1001", "name" : "Camelia", "level" : 1, "bedrooms" : 3, "Builder" : "DMCI" }
{ "_id" : "1002", "name" : "Nora", "level" : 2, "bedrooms" : 5, "Builder" : "JAP" }
{ "_id" : "1003", "name" : "Rose", "level" : 1, "bedrooms" : 2, "Builder" : "SUMICON" }
{ "_id" : "1004", "name" : "Nico", "level" : 1, "bedrooms" : 2, "Builder" : "JAP" }
{ "_id" : "1005", "name" : "Estrada", "level" : 2, "bedrooms" : 6, "Builder" : "DMCI" }
{ "_id" : "1006", "name" : "Abishai", "level" : 2, "bedrooms" : 6, "Builder" : "SUMICON" }
{ "_id" : "1007", "name" : "Erma", "level" : 2, "bedrooms" : 5, "Builder" : "DMCI" }
{ "_id" : "1008", "name" : "Dex", "level" : 2, "bedrooms" : 5, "Builder" : "DMCI" }
{ "_id" : "1009", "name" : "Lava", "level" : 1, "bedrooms" : 3, "Builder" : "JAP" }
{ "_id" : "1010", "name" : "PLUMA", "level" : 2, "bedrooms" : 5, "Builder" : "SUMICON" }
>

Grouping MongoDB Document

In this section, we’ll look at some examples where we aggregate MongoDB documents and then perform a grouping of the result.

We’ll be using the command shown below:

db.house.aggregate({ $group : {_id : "$Builder", total : { $sum : 1 }}} );

This command is equivalent to the following SQL query:

SELECT Builder, SUM(Builder) AS total
       FROM house
       GROUP BY Builder

The query shown above will select all documents and count the number of fields with the same builder. The results will then be grouped per builder.

The output should look something like this:

{ "_id" : "SUMICON", "total" : 3 }
{ "_id" : "JAP", "total" : 3 }
{ "_id" : "DMCI", "total" : 4 }

We can also add a $sort method to our query to sort our results:

db.house.aggregate(
    {
  $group : {_id : "$Builder", total : { $sum : 1 }}
    },
    {
  $sort : {total : 1}
    }
  );

The code shown above will return the same results as the following SQL query:

SELECT Builder, SUM(Builder) AS total
       FROM house
       GROUP BY Builder
       ORDER BY total ASC

Although we should receive the same result set as we did in the previous query, this set of results will be sorted in ascending order.

The result should look something like this:

{ "_id" : "SUMICON", "total" : 3 }
{ "_id" : "JAP", "total" : 3 }
{ "_id" : "DMCI", "total" : 4 }

Conclusion

When you’re performing queries in MongoDB, it can be helpful to be able to aggregate documents in a collection and then group the results. Grouping a result set makes it easier to understand and analyze your data. In this article, we showed you how to use MongoDB to aggregate and group documents; we also demonstrated how you can sort your results in addition to grouping them. With these examples to help you out, you’ll be prepared to use aggregation and grouping in your own MongoDB queries.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.