如何汇总MongoDB子文档中的每个字段? [英] How to sum every fields in a sub document of MongoDB?

查看:45
本文介绍了如何汇总MongoDB子文档中的每个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中使用db.collection.aggregate时出现问题.

I got a problem when I use db.collection.aggregate in MongoDB.

我有一个像这样的数据结构:

I have a data structure like:

_id:...

Segment:{
  "S1":1,
  "S2":5,
  ...
  "Sn":10
}

这表示Segment中的以下内容:我可能有几个带有数字值的子属性.我想将它们总结为1 + 5 + .. + 10

It means the following in Segment: I might have several sub attributes with numeric values. I'd like to sum them up as 1 + 5 + .. + 10

问题是:我不确定子属性的名称,因为对于每个文档,段号都是不同的.因此,我无法列出每个细分市场的名称.我只想使用诸如for循环之类的东西将所有值求和.

The problem is: I'm not sure about the sub attributes names since for each document the segment numbers are different. So I cannot list each segment name. I just want to use something like a for loop to sum all values together.

我尝试了以下查询:

db.collection.aggregate([

  {$group:{
    _id:"$Account",

    total:{$sum:"$Segment.$"}
])

但它不起作用.

推荐答案

您犯了一个经典错误,即具有任意字段名称. MongoDB是无模式的",但这并不意味着您无需考虑架构.键名应具有描述性,在您的情况下应为f.e. "S2"实际上没有任何含义.为了进行大多数类型的查询和操作,您将需要重新设计架构以存储数据,如下所示:

You have made the classical mistake to have arbitrary field names. MongoDB is "schema-free", but it doesn't mean you don't need to think about your schema. Key names should be descriptive, and in your case, f.e. "S2" does not really mean anything. In order to do most kinds of queries and operations, you will need to redesign you schema to store your data like this:

_id:...
Segment:[
    { field: "S1", value: 1 },
    { field: "S2", value: 5 },
    { field: "Sn", value: 10 },
]

然后,您可以像以下方式运行查询:

You can then run your query like:

db.collection.aggregate( [
    { $unwind: "$Segment" },
    { $group: {
        _id: '$_id', 
        sum: { $sum: '$Segment.value' } 
    } } 
] );

这会导致如下结果(带有您问题中的唯一文档):

Which then results into something like this (with the only document from your question):

{
    "result" : [
        {
            "_id" : ObjectId("51e4772e13573be11ac2ca6f"),
            "sum" : 16
        }
    ],
    "ok" : 1
}

这篇关于如何汇总MongoDB子文档中的每个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆