Model.aggregate()

Parameters
  • [pipeline] «Array» aggregation pipeline as an array of objects

  • [callback] «Function»

Returns:
  • «Aggregate»

Performs aggregations on the models collection.

If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.

This function triggers the following middleware.

  • aggregate()

Example:

  1. // Find the max balance of all accounts
  2. Users.aggregate([
  3. { $group: { _id: null, maxBalance: { $max: '$balance' }}},
  4. { $project: { _id: 0, maxBalance: 1 }}
  5. ]).
  6. then(function (res) {
  7. console.log(res); // [ { maxBalance: 98000 } ]
  8. });
  9. // Or use the aggregation pipeline builder.
  10. Users.aggregate().
  11. group({ _id: null, maxBalance: { $max: '$balance' } }).
  12. project('-id maxBalance').
  13. exec(function (err, res) {
  14. if (err) return handleError(err);
  15. console.log(res); // [ { maxBalance: 98 } ]
  16. });

NOTE:

  • Mongoose does not cast aggregation pipelines to the model’s schema because $project and $group operators allow redefining the “shape” of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the mongoose-cast-aggregation plugin to enable minimal casting for aggregation pipelines.
  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).

More About Aggregations: