我有一個帶有屬性 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
uj5u.com熱心網友回復:
用 $group
db.collection.aggregate([
{
"$group": {
"_id": "$UserTo",
"sum": {
"$sum": "$Amount"
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/352598.html
標籤:javascript MongoDB 猫鼬 默恩
