Navigation

collection.aggregate()

Definition

collection.aggregate()

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

Usage

Example

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}`))

To call the collection.aggregate() action from a JavaScript SDK, use the RemoteMongoCollection.aggregate() method.

const pipeline = [
  { "$group": {
      "_id": "$customerId",
      "numPurchases": { "$sum": 1 },
      "numItemsPurchased": { "$sum": { "$size": "$items" } }
  } },
  { "$addFields": {
      "averageNumItemsPurchased": {
        "$divide": ["$numItemsPurchased", "$numPurchases"]
      }
  } }
]

purchasesCollection.aggregate(pipeline).toArray()
  .then(categories => {
    console.log(`Successfully grouped purchases for ${categories.length} customers.`)
    for(const category of categories) {
      console.log(`category: ${category._id}`)
      console.log(`num purchases: ${category.numPurchases}`)
      console.log(`total items purchased: ${category.numItemsPurchased}`)
      console.log(`average items per purchase: ${category.averageNumItemsPurchased}`)
    }
    return categories
  })
  .catch(err => console.error(`Failed to group purchases by customer: ${err}`))

To call the collection.aggregate() action from the Java/Android SDK, use the RemoteMongoCollection.aggregate() method.

List<Document> aggregationPipeLine = List.of(
    new Document(
        "$group", new Document()
            .append("_id", "$customerId")
            .append("numPurchases", new Document(
                "$sum", 1
            ))
            .append("numItemsPurchased", new Document(
                "$sum", new Document("$size", "$items")
            ))
    ),
    new Document(
        "$addFields", new Document(
            "averageNumItemsPurchased", new Document(
                "$divide", List.of("$totalQuantity", "$count")
            )
        )
    )
);

purchasesCollection.aggregate(aggregationPipeLine).forEach(item -> {
    Log.d("app", String.format("aggregation result:  %s", item.toString()));
});

// Another way to iterate through
Task<List<Document>> itemsTask = purchasesCollection
    .aggregate(aggregationPipeLine)
    .into(new ArrayList<Document>());
itemsTask.addOnCompleteListener(new OnCompleteListener <List<Document>> () {
    @Override
    public void onComplete(@NonNull Task <List<Document>> task) {
        if (task.isSuccessful()) {
            List<Document> items = task.getResult();
            Log.d("app", String.format("%d aggregation results", items.size()));
            for (Document item: items) {
                Log.d("app", String.format("aggregation result:  %s", item.toString()));
            }
        } else {
            Log.e("app", "failed to perform aggregation with: ", task.getException());
        }
    }
});

To call the collection.aggregate() action from the Swift/iOS SDK, use the RemoteMongoCollection.aggregate() method.

let pipeline : [Document] = [
    [ "$group": [
        "_id": "$customerId",
        "numPurchases": ["$sum": 1] as Document,
        "numItemsPurchased": ["$sum": ["$size": "$items"] as Document] as Document,
    ] as Document] as Document,
    [ "$addFields": [
        "averageNumItemsPurchased": [
            "$divide": ["$totalQuantity", "$count"] as Document
        ] as Document
    ] as Document ] as Document
];

purchasesCollection?.aggregate(pipeline).toArray({ result in
    switch result {
    case .success(let customers):
        print("Successfully grouped purchases for \(customers.count) customers:");
        customers.forEach({ customer in
            print("customer id: \(customer._id)");
            print("num purchases: \(customer.numPurchases)");
            print("total items purchased: \(customer.numItemsPurchased)");
            print("average items purchased: \(customer.averageNumItemsPurchased)");
        })
    case .failure(let error):
        print("Failed to group purchases by customer: \(err)");
    }
})

Parameters

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

aggregate(pipeline)

The aggregate() method has the following form:

aggregate(pipeline)

The aggregate() method has the following form:

aggregate​(List<? extends Bson> pipeline, Class<ResultT> resultClass)

The aggregate() method has the following form:

aggregate(pipeline)
Parameter Description

Aggregation Pipeline

pipeline: Array<document>

An array of one or more aggregation pipeline stage documents.

Supported Aggregation Stages

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

Return Value

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))

Note

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

The RemoteMongoCollection.aggregate() method returns a RemoteMongoReadOperation object.

result: RemoteMongoReadOperation

You can access documents in the aggregation result set by calling one of the following methods on the RemoteMongoReadOperation object:

Method Description

First Document

result.first()

“”

Return a Promise that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Return a StitchResult enum to the completion handler that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Array of Documents

result.toArray()

“”

Return a Promise that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Return a StitchResult enum to the completion handler that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Query Cursor

result.iterator()

“”

Return a Promise that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

Return a StitchResult enum to the completion handler that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

The RemoteMongoCollection.aggregate() method returns a RemoteAggregateIterable object.

RemoteAggregateIterable result

You can access documents in the aggregation result set by calling one of the following methods on the RemoteAggregateIterable object:

Method Description

First Document

result.first()

Return a Task that resolves to the first document from the query result set.

See RemoteMongoIterable.first()

Array of Documents

result.into(<target>)

Iterate all documents in the query result set into the target object. Return a Task that resolves to the populated target object.

See RemoteMongoIterable.into()

For Each

result.forEach(<Block>)

Iterate over the result set and apply the given block to each document. Does not return a value.

See RemoteMongoIterable.forEach()

Map Document Type

result.map(<Function>)

Return a new iterator that maps each result document to a new type specified by the provided function.

See RemoteMongoIterable.map()

Query Cursor

result.iterator()

Return a Task that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.tryNext() method.

See RemoteMongoIterable.iterator()

The RemoteMongoCollection.aggregate() method returns a StitchResult enum to its completion handler:

enum StitchResult {
  case success(result: RemoteMongoReadOperation)
  case failure(error: StitchError)
}

If the find operation was successful, the StitchResult resolves to a RemoteMongoReadOperation object that allows you to access documents in the aggregation result set by calling one of the following methods:

Method Description

First Document

result.first()

“”

Return a Promise that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Return a StitchResult enum to the completion handler that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Array of Documents

result.toArray()

“”

Return a Promise that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Return a StitchResult enum to the completion handler that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Query Cursor

result.iterator()

“”

Return a Promise that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

Return a StitchResult enum to the completion handler that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().