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:
// Find the max balance of all accounts
Users.aggregate([
{ $group: { _id: null, maxBalance: { $max: '$balance' }}},
{ $project: { _id: 0, maxBalance: 1 }}
]).
then(function (res) {
console.log(res); // [ { maxBalance: 98000 } ]
});
// Or use the aggregation pipeline builder.
Users.aggregate().
group({ _id: null, maxBalance: { $max: '$balance' } }).
project('-id maxBalance').
exec(function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { maxBalance: 98 } ]
});
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:
当前内容版权归 mongoosejs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 mongoosejs .