mongodb - Return sum with modulus GROUP BY -


i need sum of results of query group field. explain example.

this results of find()

{ "_id" : objectid("5749a5fd7aed9ced75b94218"), "groupvalue" : "5", "weight" : 123 } { "_id" : objectid("5749a5fd7aed9ced75b94219"), "groupvalue" : "5", "weight" : 345 } { "_id" : objectid("5749a5fd7aed9ced75b9421a"), "groupvalue" : "2", "weight" : 1 } { "_id" : objectid("5749a5fd7aed9ced75b9421b"), "groupvalue" : "2", "weight" : 2 } { "_id" : objectid("5749a5fd7aed9ced75b9421c"), "groupvalue" : "5", "weight" : 567 } 

now want results sum calculated weight of groupvalue.

for example want

(123 + 345 + 567)mod(5) , (1+2)mod(2) 

solution finded: solved own solution. registered new javascript function:

db.system.js.save( { _id : "getmodulus" , value : function (x, modulus){ return x % modulus; } } ); 

now load it: db.loadserverscripts();

now create 2 function: map, reduce.

var map = function () { var key = {groupvalue: this.groupvalue}; emit(key, {weight: this.weight, groupvalue: this.groupvalue}); };  var reduce = function (key, values) { var sum = 0; var groupvalue = 0; values.foreach( function (value) { sum += value['weight']; groupvalue = value['groupvalue']; }); var number = getmodulus(sum, groupvalue); return {weight: number}; }; 

and call mapreduce:

db.hits.mapreduce(map, reduce, {out: {inline:1}}) 

try query

    db.getcollection('collectionname').aggregate( [  { $group : { _id : "$groupvalue" ,total:{$sum:"$weight"}} }, { $project : { _id:0,groupvalue : "$_id" , total : "$total" ,     remainder: { $mod: [ "$total", "$_id" ] } } }] ) 

its working fine , 1 more thing please change groupvalue field (string number) work


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -