【问题标题】:how can i get total sum of mongDB property我如何获得 mongoDB 属性的总和
【发布时间】:2021-12-21 02:22:47
【问题描述】:

我有一个具有属性 UserTo 的对象数组,每个对象都有属性 Amount ,我想添加具有相同 UserTo 的所有用户数量,我该如何在 mongoDB 或 javaScript 中做到这一点。正如您在下面的数组中看到的那样,其中许多具有相同的 UserTo 并且每个具有不同的金额,所以我想将它们的所有金额与总金额汇总在一个文档中并删除重复项

代码:

(4) [{…}, {…}, {…}, {…}]
0:
Amount: 5
CoinpackPurchasedID: "617f96255c47518b6741893c"
Level: 1
Status: "Active"

UserTo: "617f8d255c47518b674188c9"
created_at: "2021-11-01T07:24:36.962Z"
updated_at: "2021-11-01T07:24:36.962Z"
__v: 0
_id: "617f96345c47518b6741894b"
[[Prototype]]: Object


1:
Amount: 5
CoinpackPurchasedID: "617f96255c47518b6741893c"
Level: 1
Status: "Active"

UserTo: "617f8d255c47518b674188c9"
created_at: "2021-11-01T07:24:36.962Z"
updated_at: "2021-11-01T07:24:36.962Z"
__v: 0
_id: "6186558fec66b04ecb6892ce"
[[Prototype]]: Object
2:
Amount: 5
CoinpackPurchasedID: "617f96255c47518b6741893c"
Level: 1
Status: "Active"

UserTo: "617f8d255c47518b674188c9"
created_at: "2021-11-01T07:24:36.962Z"
updated_at: "2021-11-01T07:24:36.962Z"
__v: 0
_id: "61867816329e07487e91ea9b"
[[Prototype]]: Object


3:
Amount: 10
CoinpackPurchasedID: "617f96255c47518b6741893c"
Level: 2
Status: "Active"

UserTo: "617f8c9d5c47518b674188ba"
created_at: "2021-11-01T07:24:36.963Z"
updated_at: "2021-11-01T07:24:36.963Z"
__v: 0
_id: "617f96345c47518b6741894c"
[[Prototype]]: Object

【问题讨论】:

    标签: javascript mongodb mongoose mern


    【解决方案1】:

    使用$group

    db.collection.aggregate([
      {
        "$group": {
          "_id": "$UserTo",
          "sum": {
            "$sum": "$Amount"
          }
        }
      }
    ])
    

    mongoplayground

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 2013-06-07
      • 2014-02-09
      • 1970-01-01
      • 2018-10-18
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多