【问题标题】:MongoDB aggregate on multiple fieldsMongoDB 在多个字段上聚合
【发布时间】:2018-06-16 04:54:03
【问题描述】:

我只有 RDBS 的经验。可以通过多个字段聚合字段。

t_example:

country  |  city   |   val  |  useless
---------------------------------------
Ger      |  Ber    |    10  |    abc
Ger      |  Ber    |    10  |    abc
Ger      |  MU     |    10  |    abc
FR       |  Par    |    10  |    abc

SELECT country,city,sum(val) FROM t_example GROUP BY country,city;

=>

country  |  city   |   val  
----------------------------
Ger      |  Ber    |    20  
Ger      |  MU     |    10  
FR       |  Par    |    10  

如果一个集合在 JSON 文件中包含相同的值,MongoDB 是否可以获得相同的结果? 我在 NodeJS 上试过这个:

dbs.collection('t_example').aggregate([{ $group: { "_id": "$country","count":{$sum:1}}}]).toArray(function(error,result){
            res.json(result);       
        });

我得到了类似的结果:

[{"_id":"Ger","count":30},{"_id":"Fr","count":10}]

是否可以按附加字段(城市)细分数据? 我也无法更改密钥(_id)。否则结果为空数组。

【问题讨论】:

  • _id 获取文档。试试_id:{country:"$country", city:"$city"}

标签: node.js mongodb


【解决方案1】:

您可以使用以下管道。

[
  { $group: { 
    _id: { country: "$country", city: "$city" }, 
    val: { $sum: "$val" } 
  } }
]

事实上,对于小组赛来说,_idcan be a structured object

生成的文档如下所示。

[
    {
        "_id" : {
            "country" : "Fr",
            "city" : "Par"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "MU"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "Ber"
        },
        "val" : 20.0
    }
]

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多