Sumedha Gamage
Sumedha Gamage

Reputation: 148

How to apply aggregate pipeline operators for entire collection in mongodb

I have a scenario where I need to apply aggregate pipeline operator for all the properties in the collection. Here how I have achieved it.

model = { 
      age: Number ,
      risk: Number,
      retireage: Number,
      wealth:  Number
    };

I need to sum all together and get the average.

What I did:

    $group :{
             _id: '',
             age : {$avg : {$sum: ['$age',value]}},
             risk : {$avg : {$sum: ['$risk',value]}},
             retireage : {$avg : {$sum: ['$retireage',value]}},
             wealth : {$avg : {$sum: ['$wealth',value]}},

    }

Is there a way I can apply {$avg: {$sum:'$this'}} at once for all the properties in the collection.

Upvotes: 0

Views: 146

Answers (1)

YouneL
YouneL

Reputation: 8369

You have to specify an _id value of null to accumulate values of all documents and then use $sum operator to get the sum of each field :

Model.aggregate([
    { 
        $group : 
        {  
            _id: null, 
            age: { $avg: { $sum: '$age' } },
            risk: { $avg: { $sum: '$risk' } },
            retireage: { $avg: { $sum: '$retireage' } },
            wealth: { $avg: { $sum: '$wealth' } }
        } 
    }
]);

EDIT If you have multiple fields to group you can use a loop to create your query:

var fields = ['age', 'risk', 'retireage', 'wealth', ...];
    groups = { _id: null };

fields.foreach( function (field) {  
    groups[field] = { $avg: { $sum: '$' + field } };
});

Model.aggregate([
    { 
        $group : groups
    }
]);

Upvotes: 1

Related Questions