Home > Enterprise >  how can i get total sum of mongDB property
how can i get total sum of mongDB property

Time:11-09

i have an array of objects with property UserTo , each object has property Amount , i want to add all amounts of users with same UserTo , how can i do that in mongoDB or with javaScript. as u can see in array below many of them has same UserTo and each have different amount , so i want to sum all their amounts in one single document with total amounts and remove duplicates

code:

(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

CodePudding user response:

use $group

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

mongoplayground

  • Related