Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can definitely do this. I'll address your questions one at a time:</p> <p>1. You can specify a query along with your map-reduce, which filters the set of objects which will be passed into the map phase. In the mongo shell, this would look like (assuming <code>m</code> and <code>r</code> are the names of your mapper and reducer functions, respectively):</p> <pre><code>&gt; db.coll.mapReduce(m, r, {query: {$or: [{"recently-voted": true}, {"hourly-score": {$gt: 0}}]}}) </code></pre> <p>2. Step #1 will let you use your mapper on all documents with at least one vote in the last hour (or with <code>recently-voted</code> set to true), but not all the votes will have been in the last hour. So you'll need to filter the list in your mapper, and only emit those votes you wish to count:</p> <pre><code>function m() { var hour_ago = new Date() - 3600000; this.votes.forEach(function (vote) { if (vote.ts &gt; hour_ago) { emit(/* your key */, this.vote.a); } }); } </code></pre> <p>And to reduce:</p> <pre><code>function r(key, values) { var sum = 0; values.forEach(function(value) { sum += value; }); return sum; } </code></pre> <p>3. To update the hourly scores table, you can use the <code>reduceOutput</code> option to map-reduce, which will call your reducer with both the emitted values, and the previously saved value in the output collection, (if any). The result of that pass will be saved into the output collection. This looks like:</p> <pre><code>&gt; db.coll.mapReduce(m, r, {query: ..., out: {reduce: "output_coll"}}) </code></pre> <p>In addition to re-reducing output, you can use <code>merge</code> which will overwrite documents in the output collection with newly created ones (but leaving behind any documents with an <code>_id</code> different than the <code>_id</code>s created by your m-r job), <code>replace</code>, which is effectively a drop-and-create operation and is the default, or use <code>{inline: 1}</code>, which will return the results directly to the shell or to your driver. Note that when using <code>{inline: 1}</code>, your results must fit in the size allowed for a single document (16MB in recent MongoDB releases).</p> <p>(4.) You can run map-reduce jobs on secondaries ("slaves"), but since secondaries cannot accept writes (that's what makes them secondary), you can only do this when using inline output.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload