小编Bor*_*dov的帖子

MongoDB聚合组数组到键:sum值

您好我是mongodb的新手,并尝试将具有不同类型(int)的对象转换为键值对.

我有这样的集合:

{
    "_id" : ObjectId("5372a9fc0079285635db14d8"),
    "type" : 1,
    "stat" : "foobar"
},
{
    "_id" : ObjectId("5372aa000079285635db14d9"),
    "type" : 1,
    "stat" : "foobar"
},
{
    "_id" : ObjectId("5372aa010079285635db14da"),
    "type" : 2,
    "stat" : "foobar"
},{
    "_id" : ObjectId("5372aa030079285635db14db"),
    "type" : 3,
    "stat" : "foobar"
}
Run Code Online (Sandbox Code Playgroud)

我想得到这样的结果:

{
    "type1" : 2, "type2" : 1, "type3" : 1,
    "stat" : "foobar"
}
Run Code Online (Sandbox Code Playgroud)

当前正在尝试聚合组,然后将类型值推送到数组

db.types.aggregate(
    {$group : {
        _id : "$stat",
        types : {$push : "$type"}
    }}
)
Run Code Online (Sandbox Code Playgroud)

但不知道如何将不同类型相加并将其转换为关键值

/* 0 */
{ …
Run Code Online (Sandbox Code Playgroud)

mapreduce mongodb aggregation-framework

1
推荐指数
1
解决办法
4082
查看次数

标签 统计

aggregation-framework ×1

mapreduce ×1

mongodb ×1