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

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