How to group by in mongodb query?

by filiberto , in category: PHP Databases , 2 years ago

How to group by in mongodb query?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , 2 years ago

@filiberto You can use the MongoDB $group aggregation operator to group documents from a collection by a specified expression or id:


1
2
3
4
5
6
7
8
db.yourCollection.aggregate([
    {
        "$group": {
            "_id": { key: "$someValue" }, 
            "total": { "$sum": "$someValue" }
        }
    }
])
by herminia_bruen , 8 months ago

@filiberto 

In the above example, replace yourCollection with the name of your collection and someValue with the field from your documents that you want to group by.


The $group operator has two fields:

  1. _id: The expression or field to group documents by. In the example, we group by the someValue field, but you can change it to any field you want.
  2. total: The aggregation operation you want to perform on the grouped documents. In the example, we calculate the sum of the someValue field for each group, but you can change it to any valid aggregation operation.


The result of the query will be a list of documents where each document represents a group.


Note: Make sure you have the proper indexes on the fields you are grouping by to ensure optimal query performance.