Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 多字段上的MongoDB聚合_Node.js_Mongodb - Fatal编程技术网

Node.js 多字段上的MongoDB聚合

Node.js 多字段上的MongoDB聚合,node.js,mongodb,Node.js,Mongodb,我只有使用RDB的经验。可以通过多个字段聚合字段 t_example: country | city | val | useless --------------------------------------- Ger | Ber | 10 | abc Ger | Ber | 10 | abc Ger | MU | 10 | abc FR | Par |

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

t_example:

country  |  city   |   val  |  useless
---------------------------------------
Ger      |  Ber    |    10  |    abc
Ger      |  Ber    |    10  |    abc
Ger      |  MU     |    10  |    abc
FR       |  Par    |    10  |    abc
按国家、城市从t_示例组中选择国家、城市、总和(val)

=>

如果集合在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)。否则结果将是一个空数组。

您可以使用以下管道

[
  { $group: { 
    _id: { country: "$country", city: "$city" }, 
    val: { $sum: "$val" } 
  } }
]
事实上,对于小组阶段,
\u id

生成的文档如下所示

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

_id接受文档。请尝试{code>id:{country:$country',city:$city}
[
    {
        "_id" : {
            "country" : "Fr",
            "city" : "Par"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "MU"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "Ber"
        },
        "val" : 20.0
    }
]