Mongo and Pivot

后端 未结 2 603
野趣味
野趣味 2021-01-06 03:32

I need help with mongo in this problem: I have collection stats (UserId, EventId, Count, Date) in collection are data

UserID | EventId | Count | Date

2条回答
  •  情歌与酒
    2021-01-06 04:07

    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.

提交回复
热议问题