I'm trying to learn MapReduce function in MongoDB. Instead of using an aggregation, I want to group documents in collection by key defined by myself using MapReduce function.
My collection Cool is:
/* 1 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a55"), "id" : "a", "cool" : "a1" }
/* 2 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a56"), "id" : "a", "cool" : "a2" }
/* 3 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a57"), "id" : "b", "cool" : "b1" }
/* 4 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a58"), "id" : "b", "cool" : "b2" }
/* 5 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a59"), "id" : "c", "cool" : "c1" }
/* 6 */ { "_id" : ObjectId("55d5e7287e41390ea7e83a5a"), "id" : "d", "cool" : "d1" }
Here is my MapReduce function:
db.Cool.mapReduce(
function(){emit(this.id, this.cool)},
function(key, values){
var res = [];
values.forEach(function(v){
res.push(v);
});
return {cools: res};
},
{out: "MapReduce"}
)
I want get result like that:
/* 1 */ { "_id" : "a", "value" : { "cools" : [ "a1", "a2" ] } }
But in the returning collection, there are:
/* 1 */ { "_id" : "a", "value" : { "cools" : [ "a1", "a2" ] } }
/* 2 */ { "_id" : "b", "value" : { "cools" : [ "b1", "b2" ] } }
/* 3 */ { "_id" : "c", "value" : "c1" }
/* 4 */ { "_id" : "d", "value" : "d1" }
The question is: why there a different between document "id":"a" (there are more than one document of "id":"a") and document of "id":"c" (there is only one document of "id":"c")
Thanks for any suggestion and sorry for my bad English.