MongoDB Documentation, Release 3.0.4 7.3.4 Perform Incremental Map-Reduce Data Setup Initial Map-Reduce of Current Collection Map-reduce operations can handle complex aggregation tasks. To perform map-reduce operations, MongoDB provides the mapReduce command and, in the mongo shell, the db.collection.mapReduce() wrapper method. If the map-reduce data set is constantly growing, you may want to perform an incremental map-reduce rather than performing the map-reduce operation over the entire data set each time. To perform incremental map-reduce: Consider the following example where you schedule a map-reduce operation on a sessions collection to run at the end of each day. The sessions collection contains documents that log users’ sessions each day, for example: db.sessions.save( { userid: "a", ts: ISODate('2011-11-03 14:17:00'), length: 95 } ); db.sessions.save( { userid: "b", ts: ISODate('2011-11-03 14:23:00'), length: 110 } ); db.sessions.save( { userid: "c", ts: ISODate('2011-11-03 15:02:00'), length: 120 } ); db.sessions.save( { userid: "d", ts: ISODate('2011-11-03 16:45:00'), length: 45 } ); db.sessions.save( { userid: "a", ts: ISODate('2011-11-04 11:05:00'), length: 105 } ); db.sessions.save( { userid: "b", ts: ISODate('2011-11-04 13:14:00'), length: 120 } ); db.sessions.save( { userid: "c", ts: ISODate('2011-11-04 17:00:00'), length: 130 } ); db.sessions.save( { userid: "d", ts: ISODate('2011-11-04 15:37:00'), length: 65 } ); var mapFunction = function () { var key = this .userid; var value = { userid: this .userid, total_time: this .length, count: 1, avg_time: 0 }; emit( key, value ); }; 1. Define the map function that maps the userid to an object that contains the fields userid , total_time , count , and avg_time : 2. Define the corresponding reduce function with two arguments key and values to calculate the total time and the count. The key corresponds to the userid , and the values is an array whose elements corresponds to the individual objects mapped to the userid in the mapFunction . 463 7.3. Aggregation Examples Run the first map-reduce operation as follows: • the out parameter that specifies the reduce action to merge the new results into the existing output collection. • the query parameter that specifies conditions that match only the new documents. 2. When you have more data to process, run subsequent map-reduce job with: 1. Run a map-reduce job over the current collection and output the result to a separate collection.