Docs Menu


On this page

  • Definition
  • Usage
  • Example
  • Parameters
  • Return Value

Execute an aggregation pipeline and return a handle object that allows you to access the pipeline's output documents.

To call the collection.aggregate() action from a Function, get a collection handle with database.collection() then call the handle's aggregate() method.

const pipeline = [
{ "$group": {
"_id": "$customerId",
"numPurchases": { "$sum": 1 },
"numItemsPurchased": { "$sum": { "$size": "$items" } }
} },
{ "$addFields": {
"averageNumItemsPurchased": {
"$divide": ["$numItemsPurchased", "$numPurchases"]
} }
return purchasesCollection.aggregate(pipeline).toArray()
.then(customers => {
console.log(`Successfully grouped purchases for ${customers.length} customers.`)
for(const customer of customers) {
console.log(`customer: ${customer._id}`)
console.log(`num purchases: ${customer.numPurchases}`)
console.log(`total items purchased: ${customer.numItemsPurchased}`)
console.log(`average items per purchase: ${customer.averageNumItemsPurchased}`)
return customers
.catch(err => console.error(`Failed to group purchases by customer: ${err}`))

The collection.aggregate() action has the following form:


Aggregation Pipeline

pipeline: Array<document>

An array of one or more aggregation pipeline stage documents.

Supported Aggregation Stages

MongoDB Realm supports nearly all MongoDB aggregation pipeline stages and operators, but some stages and operators must be executed within a system function. See Aggregation Framework Limitations for more information.

The collection.aggregate() action returns a cursor object that points to any documents output from the final stage of the aggregation pipeline. You can manipulate and access documents in the aggregation result set with the following methods:


Iterates the cursor and returns a Promise that resolves to the next document in the cursor. If the cursor is exhausted, the promise resolves to undefined.

.then(doc => console.log("next document", doc))

Iterates the cursor to exhaustion and returns a Promise that resolves to an array that contains all of the iterated documents.

.then(docs => console.log("all documents", docs))

Specifies a number of matching documents to omit from the aggregation result set. MongoDB omits documents from the result set in sort order until it has skipped the specified number.


You cannot call this method after retrieving one or more documents using or cursor.toArray().

Client Session

session: <ClientSession>
Optional. A client session that specifies the transaction context in which the operation occurs. To learn more, see Transactions.

You cannot return a cursor from a Function. Instead, evaluate the cursor using or cursor.toArray() and return the result.

Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.