Navigation

collection.aggregate()

collection.aggregate()

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: ${_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:

aggregate(pipeline)
Parameter
Description

Aggregation Pipeline

pipeline: Array<document>

An array of one or more aggregation pipeline stage documents.

Note
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:

Method
Description
cursor.next()

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.

Example
collection.aggregate(pipeline).next()
.then(doc => console.log("next document", doc))
cursor.toArray()

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

Example
collection.aggregate(pipeline).toArray()
.then(docs => console.log("all documents", docs))
cursor.skip(amount)

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.

Note

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

Note

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

Give Feedback