Asked 7 years ago
24 Jan 2017
Views 1060
ajamil

ajamil posted

how to GroupBy multiple columns in MongoDB ?

how to GroupBy multiple columns in MongoDB ?
Mahesh Radadiya

Mahesh Radadiya
answered Apr 24 '23 00:00

When working with MongoDB, you can use the aggregate pipeline to group documents by multiple columns. To do this, you can use the $group stage of the pipeline, which allows you to group documents based on specific fields.

Here's an example query that groups documents by multiple columns:



db.collection.aggregate([
  {
    $group: {
      _id: { field1: "$field1", field2: "$field2" },
      count: { $sum: 1 }
    }
  }
]);

In this example, we're grouping the documents in the collection by field1 and field2 , and then counting the number of documents in each group using the $sum operator.

The result of this query will be a list of documents with _id and count fields. The _id field will be an object with field1 and field2 properties representing the group key, and the count field will be the number of documents in each group.

Keep in mind that the syntax of MongoDB queries may vary depending on the version of MongoDB and the driver used. The example shown here is for MongoDB 4.0 and later.
Post Answer