JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Grouping values by multiple fields with MongoDB

Author:JIYIK Last Updated:2025/04/29 Views:

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 $groupthe operator, which helps in performing multiple other aggregation functions on the grouped data.

This article will discuss the various ways to use operators in MongoDB to group values ​​by multiple fields within a document. It will also look at the list of operators used with aggregation and how to implement them with the help of examples.

$groupOperators in MongoDB

The MongoDB $groupoperator is nothing more than a written record of the database with input and output of several aggregate fields. It accepts a single document and returns one or more documents.

When grouping on individual fields, you can use various operators, as described below.

Aggregation pipeline

Another way to group fields in MongoDB is by using pipes when POSIXmode is set to . Using the polymer pipe function, you can filter out documents that match the criteria of an aggregation pipeline.true

Define stage operators for each level of the aggregation pipeline. Stage operators can use expression operators internally to wrap before each level stage and even calculate averages or sums or concatenate specific values.

The output of an aggregation pipeline is considered the final output to be returned, and it can even be stored in a collection if needed.

Processing Flow

Another way to group multiple fields is to use processing streams. You can use Db.collection.aggregate()functions to process data simultaneously using various channels.

Db.collection.aggregate()Functions internally do aggregation and provide support for multiple operations to be used.

Db.collection.aggregate()The function can be used efficiently on a series of slices without causing data loss. The function Db.collection.aggregate()returns the data stored in memory as a cursor that can be used directly as MongoShell.

$groupOperator Examples in MongoDB

You can use the following collections in this article.

db={
  "invoice": [
    {
      "_id": 1,
      "item": "apple",
      "qty": 20,
      "rate": 10,
      "inv_date": "02/02/2020"
    },
    {
      "_id": 2,
      "item": "orange",
      "qty": 15,
      "rate": 8,
      "inv_date": "05/12/2020"
    },
    {
      "_id": 3,
      "item": "mango",
      "qty": 25,
      "rate": 8,
      "inv_date": "07/02/2020"
    },
    {
      "_id": 4,
      "item": "apple",
      "qty": 20,
      "rate": 10,
      "inv_date": "02/02/2020"
    },
    {
      "_id": 5,
      "item": "mango",
      "qty": 10,
      "rate": 8,
      "inv_date": "05/12/2020"
    },
    {
      "_id": 6,
      "item": "apple",
      "qty": 30,
      "rate": 10,
      "inv_date": "13/04/2020"
    },
    {
      "_id": 7,
      "item": "orange",
      "qty": 15,
      "rate": 8,
      "inv_date": "05/12/2020"
    },
    {
      "_id": null,
      "item": "banana",
      "qty": 10,
      "rate": 20,
      "inv_date": "17/12/2020"
    },

  ]
}

The following example groups by the Invoice Date field and displays the total cost, average quantity, and invoice quantity for the same date.

db.invoice.aggregate([
  {
    $group: {
      _id: "$inv_date",
      totalCost: {
        $sum: {
          $multiply: [
            "$rate",
            "$qty"
          ]
        }
      },
      avgQty: {
        $avg: "$qty"
      },
      count: {
        $sum: 1
      }
    }
  }
])

The result shows that the documents for the field Invoice Date are grouped and the total cost, average quantity, and number of invoices issued for that date are displayed.

Grouping Value

$groupAbout Multiple Keys in MongoDB

The following example groups by Invoice Date, then by the Item field, and displays the total cost, average quantity, and invoice quantity for the same date.

db.invoice.aggregate([
  {
    $group: {
      _id: {
        inv_date: "$inv_date",
        item: "$item"
      },
      totalCost: {
        $sum: {
          $multiply: [
            "$rate",
            "$qty"
          ]
        }
      },
      avgQty: {
        $avg: "$qty"
      },
      count: {
        $sum: 1
      }
    }
  }
])

The results below show that documents with InvoiceDate 05/12/2020and 02/02/2020have the same items; the combination of these two fields forms a group.

Group Value 1

Multiple keys $groupused in MongoDB$match

The following example groups by Invoice Date, then by the Item field, and displays 05/12/2020the total cost, average quantity, and invoice number on the same date for those documents with an invoice date of .

db.invoice.aggregate([
  {
    $match: {
      inv_date: "05/12/2020"
    }
  },
  {
    $group: {
      _id: {
        inv_date: "$inv_date",
        item: "$item"
      },
      totalCost: {
        $sum: {
          $multiply: [
            "$rate",
            "$qty"
          ]
        }
      },
      avgQty: {
        $avg: "$qty"
      },
      count: {
        $sum: 1
      }
    }
  }
])

The result below shows that 05/12/2020there are three invoices for the document with invoice date , but with the same item combination, which have been grouped together.

Group value 2

$groupDistinguishing Values ​​in MongoDB

The following aggregation operation uses $groupthe stage to group documents by item to retrieve distinct item values.

db.invoice.aggregate([
  {
    $group: {
      _id: "$item"
    }
  }
])

The output is shown in the screenshot below.

Group value 3

$groupGroup invoice dates by stage in MongoDB

The following aggregation operation uses $groupstage to group the invoice dates of the documents by project.

db.invoice.aggregate([
  {
    $group: {
      _id: "$item",
      invoiceDate: {
        $push: "$inv_date"
      }
    }
  }
])

The screenshot below is the output.

Group value 4

This article teaches you $groupthe most efficient way to group multiple fields present in a MongoDB document using the operator.

It also discusses all the various forms of using operators in MongoDB and a list of operators used with aggregation and how to implement them with the help of examples.

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.

Article URL:

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;

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial