Dino Geek, try to help you

How to use group operator in MongoDB?


The `$group` operator in MongoDB is used to group documents by some specified expression and output for each distinct grouping a document that contains the `_id` and the accumulated results for each group.

Here’s an example:

Assume we have a collection named `orders` with documents structured like:

```
[ { “_id”: 1, “item”: “apple”, “price”: 10, “quantity”: 10 }, { “_id”: 2, “item”: “banana”, “price”: 20, “quantity”: 15 }, { “_id”: 3, “item”: “apple”, “price”: 10, “quantity”: 20 }, { “_id”: 4, “item”: “banana”, “price”: 20, “quantity”: 10 },
]
```

If you want to calculate the total cost for each item(`totalCost = price * quantity`), you can group by `item` and use the `$sum` operator:

```
db.orders.aggregate( [ { $group: { _id: “$item”, // Indicate the field we want to group by totalCost: { // The new field will contain the result of the following operation $sum: { $multiply: [ “$price”, “$quantity” ] } // Multiply price with quantity and then sum it } } } ]
)
```

The query above will return:

```
[ { “_id”: “apple”, “totalCost”: 300 }, { “_id”: “banana”, “totalCost”: 500 },
]
```

Where `_id` is the value by which documents are grouped.

In this example, we used the `$multiply` and `$sum` operators, but there are many other operators that can be used with `$group` like `$avg`, `$first`, `$last`, `$max`, `$min`, `$push`, `$addToSet`, etc.

The general syntax of the `$group` operator is:

```
{ $group: { _id: , : { : }, … } }
```


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use