MongoDB Map Reduce - complete to skip some results

I have a map reduction function that works in the collection as follows:

function Map() { emit ( this.name, { count : 1, flag : this.flag } ); } function Reduce(key, values) { var count = 0; var flag = false; for (var i in values){ count = count + 1; if (i.flag) flag = true; } var reduced = { count : count, flag : flag } return reduced; } function Finalize(key, reduced) { if (reduced.count>10 || reduced.flag){ var finalized = { "count" : reduced.count } return reduced; } return null; } 

What I'm trying to do is that Finalize will only return objects that pass a specific threshold (e.g. count> 10). Currently, it still returns objects, and the counter is zero.

Any ideas?

+4
source share
1 answer

I would suggest you use the aggregation structure instead, since it is much faster and more understandable. Your above M / R / F can be written as easily as:

 db.so.insert( { name: "Derick" } ); db.so.insert( { name: "Derick" } ); db.so.insert( { name: "Derick" } ); db.so.insert( { name: "Derick" } ); db.so.insert( { name: "Checklist" } ); db.so.insert( { name: "Checklist" } ); db.so.insert( { name: "Whoop" } ); db.so.insert( { name: "Whoop", flagged: true } ); db.so.aggregate( [ { $group: { _id: '$name', count: { $sum: 1 }, flagged: { $sum: { $cond: [ { $eq: [ '$flagged', true ] }, 1, 0 ] } } } }, { $match: { $or: [ { count: { $gt: 3 } }, { flagged: { $gt: 0 } } ] } } ] ); 

What returns:

 { "result" : [ { "_id" : "Whoop", "count" : 2, "flagged" : 1 }, { "_id" : "Derick", "count" : 4, "flagged" : 0 } ], "ok" : 1 } 
+1
source

Source: https://habr.com/ru/post/1495351/


All Articles