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

查看:15
本文介绍了如何汇总 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天全站免登陆