【问题标题】:How to write group by query for embedded array of document in mongodb如何通过查询为mongodb中的嵌入式文档数组编写分组
【发布时间】:2020-11-19 04:10:24
【问题描述】:

我有一个以下格式的集合

{customerID:1,acctDetails:[{accType:"Saving",balance:100},{accType:"checking",balance:500}]}
{customerID:2,acctDetails:[{accType:"Saving",balance:500}]}

我想通过 acctType 找到总余额。我试过下面的查询。

db.<collectionName>.aggregate([{$group:{_id:"$acctDetails.accType",totalBalance:{$sum:"$accDetails.balace"}}}])

但它没有给出正确的结果。

【问题讨论】:

标签: mongodb


【解决方案1】:

我认为这可能会解决您的问题。您首先需要使用$unwind 转换文档中的每个数组元素,然后使用$group 对账户类型的总余额求和。

db.collection.aggregate([
  {"$unwind": "$acctDetails"},
  {
    "$group": {
      "_id": "$acctDetails.accType",
      "totalBalance": {"$sum": "$acctDetails.balance"}
    }
  }
])

工作Mongo playground

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 2021-03-24
    • 2015-02-06
    • 1970-01-01
    • 2015-08-30
    • 2021-04-14
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多