i am trying to write a mapreduce function to accumulate statistics from a mongodb. However.. My teammate who created the data structure saved the data as followed:
"statistics": {
"20111206": {
"CN": {
"Beijing": {
"cart": 1,
"cart_users": [
{ "$oid" : "4EDD73938EAD0E5420000000" }
],
"downloads": {
"wmv": {
"mid": 1
}
},
"orders": {
"wmv": {
"mid": 1
}
}
}
}
}
}
The Problem is that a lot of values i need to group by are just stored in the keys (like CN or BEJING in the example) . These can be country codes, video formats etc... so i dont want to harcode any of these in the mapreduce function.
The forEach function which i used for the reduce part only passes in the values as an argument..
So the question is: is there any way to perform a mapReduce on this and group by keys or must i first convert the data into a new structure which looks more or less somthing like this:
{
"movie_id": "4edcd4f29a4e61c00c000059",
"country": "CN",
"city": "Beijing",
"list": [
{
"user_id": { "$oid" : "4EDD75388EAD0E5720010000" },
"downloads": {
"cnt": 1,
"list": [
{
"format": "wmv",
"quality": "high"
}
]
},
"orders": {
"cnt": 1,
"list": [
{
"format": "wmv",
"quality": "high"
}
]
}
}
]
}
Say your collection is set up with records like the following:
> db.test_col.findOne()
{
"_id" : ObjectId("4f90ed994d2246dd7996e042"),
"statistics" : {
"20111206" : {
"CN" : {
"Beijing" : {
"cart" : 1,
"cart_users" : [
{
"oid" : "4EDD73938EAD0E5420000000"
}
],
"downloads" : {
"wmv" : {
"mid" : 1
}
},
"orders" : {
"wmv" : {
"mid" : 1
}
}
}
}
}
}
}
Here's a command that will group by country, provide a list of cities, and total count for the country. It should get you closer to what you
are
were trying to do:
db.runCommand({ mapreduce: "test_col",
map: function () {
var l0 = this.statistics,
date = Object.keySet(l0)[0],
l1 = l0[date],
country = Object.keySet(l1)[0],
l2 = l1[country],
city = Object.keySet(l2)[0],
data = l2[city];
emit(country, { date: date, city: city, data: data });
},
reduce: function (country, values) {
var r = { cities: [], count: 0 };
values.forEach(function (v) {
if (r.cities.indexOf(v.city) == -1) r.cities.push(v.city);
r.count++;
});
return r;
},
out: { reduce: "test_col_reduce" }
});
The output for my test data looks like this:
> db.test_col_reduce.find()
{ "_id" : "AR", "value" : { "cities" : [ "San Juan", "Buenos Aires", "Cordoba", "Rosario" ], "count" : 18 } }
{ "_id" : "BZ", "value" : { "cities" : [ "Morico", "San Ignacio", "Corozal" ], "count" : 15 } }
{ "_id" : "CN", "value" : { "cities" : [ "Beijing", "Shanghai", "HongKong" ], "count" : 26 } }
{ "_id" : "US", "value" : { "cities" : [ "San Diego", "Los Angeles", "San Francisco", "New York" ], "count" : 27 } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.