如何使用mongoose从mongodb收集文档中计算字段的和

时间:2022-09-11 19:27:33

I want to perform sum of employee points from mongodb documents.

我想执行mongodb文档的员工点和。

My Documents in Employee Points Collections are like below

我在员工积分集合中的文档如下所示

[
    {
        "EmployeeID": "Cust0001",
        "Point": 1,
    },
    {
        "EmployeeID": "Cust0002",
        "Point": 2,
    },
    {
        "EmployeeID": "Cust0003",
        "Point": 1,
    },
    {
        "EmployeeID": "Cust0001",
        "Point": 5,
    },
    {
        "EmployeeID": "Cust0001",
        "Point": 2,
    }
]

Expected result

预期的结果

[
    {
        "EmployeeID": "Cust0001",
        "Total_Points": 8
    },
    {
        "EmployeeID": "Cust0002",
        "Total_Points": 2
    },
    {
        "EmployeeID": "Cust0003",
        "Total_Points": 1
    }
]

Which is the best and most optimized way to get the output from mongodb with the total points.

这是利用全局点从mongodb中获取输出的最佳和最优的方法。

I am using mongoose mongodb connection in my project.

我在我的项目中使用mongoose mongodb连接。

I can manipulate data using a for loop but it seems rather inefficent.

我可以使用for循环来操作数据,但它似乎并不有效。

Thanks in advance.

提前谢谢。

Comments are appreciated.

评论是感激。

1 个解决方案

#1


3  

You need to use $sum twice here... One as "accumulator" for $group stage and one for summation of Points

这里你需要用$sum两次…一个作为$group stage的“累加器”,另一个作为点的求和

db.collection.aggregate([
  {
    $group: {
      _id: "$EmployeeID",
      Point: {
        $sum: {
          $sum: "$Point"
        }
      }
    }
  },
  {
    $project: {
      EmployeeID: "$_id",
      Point: "$Point",
      _id: 0
    }
  }
])

Ouput

输出

[
  {
    "EmployeeID": "Cust0003",
    "Point": 1
  },
  {
    "EmployeeID": "Cust0002",
    "Point": 2
  },
  {
    "EmployeeID": "Cust0001",
    "Point": 8
  }
]

Check it here

检查在这里

#1


3  

You need to use $sum twice here... One as "accumulator" for $group stage and one for summation of Points

这里你需要用$sum两次…一个作为$group stage的“累加器”,另一个作为点的求和

db.collection.aggregate([
  {
    $group: {
      _id: "$EmployeeID",
      Point: {
        $sum: {
          $sum: "$Point"
        }
      }
    }
  },
  {
    $project: {
      EmployeeID: "$_id",
      Point: "$Point",
      _id: 0
    }
  }
])

Ouput

输出

[
  {
    "EmployeeID": "Cust0003",
    "Point": 1
  },
  {
    "EmployeeID": "Cust0002",
    "Point": 2
  },
  {
    "EmployeeID": "Cust0001",
    "Point": 8
  }
]

Check it here

检查在这里