Reputation: 9153
I have the following documents:
{ "col1": "camera", "fps": "1F", "device": "Multi" },
{ "col1": "camera", "fps": "3F", "device": "Multi" }
{ "col1": "recorders", "fps": "9F", "device": "VideoPlayer" }
{ "col1": "cell", "fps": "8F", "device": "camcorder" }
{ "col1": "cell", "fps": "3F", "device": "camcorder" }
{ "col1": "phone", "fps": "3F", "device": "camcorder" }
....and I'm trying to create a pivot table that looks like the following:
{ _id: "col1", [ { "camcorder": { "3F": 2, "8F": 1 }}, { "VideoPlayer": { "9F": 1 }}, { "Multi": { "3F":1, "1F":1" }} ] }
I'm doing the following:
map = function() { key = "col1"; value = { this.fps: device }; print(value.foo); emit(key, value); }
reduce2 = function(key, value) { retval = {}; key = value; retval[key] = (retval[key] || 0) + 1; return retval; }
This is not really working, it's resulting in the following:
{ "_id" : "col1", "value" : { "[object Object],multi,videoplayer,camcorder" : 1 } }
Basically, this will be a sum of fps, grouped by device.
Please help.
Upvotes: 0
Views: 759
Reputation: 516
I know that my suggestion is not exactly what you want, but maybe it could help you somehow.
var aggregated = db.coll.aggregate({$group: {_id:{device:"$device", fps:"$fps"
}, count: {$sum:1}}}, {$project: {device: '$_id.device', fps: '$_id.fps', count:
'$count'}}, {$group:{_id:"$device", result:{$push:{"fps":"$fps","count":"$count
"}}}})
The result will be:
{
"result" : [
{
"_id" : "Multi",
"result" : [
{
"fps" : "3F",
"count" : 1
},
{
"fps" : "1F",
"count" : 1
}
]
},
{
"_id" : "camcorder",
"result" : [
{
"fps" : "3F",
"count" : 2
},
{
"fps" : "8F",
"count" : 1
}
]
},
{
"_id" : "VideoPlayer",
"result" : [
{
"fps" : "9F",
"count" : 1
}
]
}
],
"ok" : 1
}
I think then it's not hard to merge grouped documents.
Upvotes: 2