MongoDB Aggregation

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Introduction

Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation: the aggregation pipeline, the map-reduce function, and single purpose aggregation methods.

From Mongo manual https://docs.mongodb.com/manual/aggregation/

Syntax

  • db.collection.aggregate(pipeline, options)

Parameters

ParameterDetails
pipelinearray(A sequence of data aggregation operations or stages)
optionsdocument(optional, available only if pipeline present as an array)

Remarks

Aggregation framework in MongoDB is used to achieve common GROUP BY functionality of SQL.

Consider the following insertions in collection named transactions for every example.

> db.transactions.insert({ cr_dr : "D", amount : 100, fee : 2});
> db.transactions.insert({ cr_dr : "C", amount : 100, fee : 2});
> db.transactions.insert({ cr_dr : "C", amount : 10,  fee : 2});
> db.transactions.insert({ cr_dr : "D", amount : 100, fee : 4});
> db.transactions.insert({ cr_dr : "D", amount : 10,  fee : 2});
> db.transactions.insert({ cr_dr : "C", amount : 10,  fee : 4});
> db.transactions.insert({ cr_dr : "D", amount : 100, fee : 2});


Got any MongoDB Question?