I need help with mongo in this problem: I have collection stats (UserId, EventId, Count, Date) in collection are data
You have to do this with a MapReduce operation.
Your map function would look like this: (untested!):
var mapFunction = function() {
var ret = {};
ret["Count_Event_" + this.EventId] = this.Count;
emit(this.UserId, ret);
};
This emits a series of pairs consisting of the UserId and an object with a single, differently-named attribute with the count as a value.
Your reduce function would then combine the results into one (untested - I am not sure if you can just increment a non-existing property and I can't test it right now):
var reduceFunction = function(UserId, values_array) {
var ret = {};
for (var i = 0; i < values_array.length; i++) {
var values = values_array[i];
for (key in values) {
ret[key] += values[key]; // Can you increment a non-existing attribute? Not sure, try it, please.
}
}
return ret;
};
You then call this like this:
db.yourCollection.mapReduce(
mapFunction,
reduceFunction,
out: { inline: 1 }
)
The line out: { inline: 1 } outputs the results into the console. Usually you use MapReduce to create a new collection with the results. See the documentation for more information.