Bor*_*dov 1 mapreduce mongodb aggregation-framework
您好我是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 */
{
"result" : [
{
"_id" : "foobar",
"types" : [
1,
2,
2,
3
]
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
对于您的实际表单,并因此假设您实际知道"类型"的可能值,那么您可以通过两个$group阶段和一些$cond运算符的使用来执行此操作:
db.types.aggregate([
{ "$group": {
"_id": {
"stat": "$stat",
"type": "$type"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.stat",
"type1": { "$sum": { "$cond": [
{ "$eq": [ "$_id.type", 1 ] },
"$count",
0
]}},
"type2": { "$sum": { "$cond": [
{ "$eq": [ "$_id.type", 2 ] },
"$count",
0
]}},
"type3": { "$sum": { "$cond": [
{ "$eq": [ "$_id.type", 3 ] },
"$count",
0
]}}
}}
])
Run Code Online (Sandbox Code Playgroud)
这完全给出了:
{ "_id" : "foobar", "type1" : 2, "type2" : 1, "type3" : 1 }
Run Code Online (Sandbox Code Playgroud)
我实际上更喜欢具有两个$group阶段的更动态的形式:
db.types.aggregate([
{ "$group": {
"_id": {
"stat": "$stat",
"type": "$type"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.stat",
"types": { "$push": {
"type": "$_id.type",
"count": "$count"
}}
}}
])
Run Code Online (Sandbox Code Playgroud)
不同的输出但功能和灵活的值:
{
"_id" : "foobar",
"types" : [
{
"type" : 3,
"count" : 1
},
{
"type" : 2,
"count" : 1
},
{
"type" : 1,
"count" : 2
}
]
}
Run Code Online (Sandbox Code Playgroud)
否则,如果您需要相同的输出格式但需要灵活的字段,那么您始终可以使用mapReduce,但它不是完全相同的输出.
db.types.mapReduce(
function () {
var obj = { };
var key = "type" + this.type;
obj[key] = 1;
emit( this.stat, obj );
},
function (key,values) {
var obj = {};
values.forEach(function(value) {
for ( var k in value ) {
if ( !obj.hasOwnProperty(k) )
obj[k] = 0;
obj[k]++;
}
});
return obj;
},
{ "out": { "inline": 1 } }
)
Run Code Online (Sandbox Code Playgroud)
并且在典型的mapReduce风格中:
"results" : [
{
"_id" : "foobar",
"value" : {
"type1" : 2,
"type2" : 1,
"type3" : 1
}
}
],
Run Code Online (Sandbox Code Playgroud)
但那些是你的选择