ZBLOG

mongodb group by

In MongoDB, the group() method is used to group the documents in a collection by a specified field(s) and perform some aggregation functions on the grouped data.

The syntax for the group() method is as follows:

db.collection.group(
   {
      key: <grouping_field>,
      reduce: <aggregation_function>,
      initial: <initial_value>
   }
)

Here,

  • collection is the name of the collection to be grouped.
  • key specifies the field(s) by which the documents should be grouped. This can be a single field or multiple fields separated by commas.
  • reduce specifies the aggregation function to be performed on the grouped data. This function must be written in JavaScript and takes two arguments - key (the grouping key) and values (an array of values corresponding to the grouping key).
  • initial specifies the initial value that is passed as an argument to the reduce function.

For example, let’s say we have a collection orders with the following documents:

{
   "_id": 1,
   "product": "apple",
   "quantity": 2,
   "price": 1.99
},
{
   "_id": 2,
   "product": "banana",
   "quantity": 3,
   "price": 0.99
},
{
   "_id": 3,
   "product": "orange",
   "quantity": 5,
   "price": 1.49
},
{
   "_id": 4,
   "product": "apple",
   "quantity": 4,
   "price": 1.99
}

We can use the group() method to group the documents by the product field and calculate the total revenue generated by each product using the following command:

db.orders.group(
   {
      key: { product: 1 },
      reduce: function(obj, prev) { prev.total += obj.quantity * obj.price; },
      initial: { total: 0 }
   }
)

This will return the following output:

[
   {
      "product": "apple",
      "total": 15.96
   },
   {
      "product": "banana",
      "total": 2.97
   },
   {
      "product": "orange",
      "total": 7.45
   }
]

Here, the documents have been grouped by the product field and the total revenue generated by each product has been calculated using the reduce() function. The initial value for the total revenue calculation is 0.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=773

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?