简体   繁体   中英

how to sum nominal by _id method ? nested array

 let data = [{ _id: '6081710355cebfa52c91f006', number: '081218302334', method: { deposite: 0, withdraw: 0, _id: '6081702cef267a9d14f08097', name: 'mandiri', __v: 0 }, nominal: 150000, member: '607ecffc03e9bd6a4dc24861', admin: 'dhimas hertianto', __v: 0 }, { _id: '6081711555cebfa52c91f007', number: '081218302334', method: { deposite: 0, withdraw: 0, _id: '60817032ef267a9d14f08098', name: 'bca', __v: 0 }, nominal: 17000, member: '607ecffc03e9bd6a4dc24861', admin: 'dhimas hertianto', __v: 0 }, { _id: '6081711555cebfa52c91f007', number: '081218302334', method: { deposite: 0, withdraw: 0, _id: '60817032ef267a9d14f08098', name: 'bca', __v: 0 }, nominal: 17000, member: '607ecffc03e9bd6a4dc24861', admin: 'dhimas hertianto', __v: 0 } ]

and expected:

[
  {
    id : ,
    name : mandiri,
    nominal : 15000
  },
  {
    id : ,
    name : bca,
    nominal : 34000
  },
]

Demo - https://mongoplayground.net/p/diw-TzIQP4P

Use $group and $sum

db.collection.aggregate([
  {
    $group: { _id: "$method.name", nominal: { $sum: "$nominal" } }
  },
  {
    $project: { _id: 0, name: "$_id", nominal: 1 }
  }
])

[
  {
    "name": "bca",
    "nominal": 34000
  },
  {
    "name": "mandiri",
    "nominal": 150000
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM