Skip to content

Aggregation

aggregate(pipeline) runs a MongoDB aggregation pipeline on one collection.

import { DriveDB } from '@faeizfurqan/drivedb';
const db = new DriveDB(process.env.DRIVEDB_URL!).db();
const clients = db.collection('clients');
// Pipeline value per status, biggest first
const byStatus = await clients
.aggregate([
{ $match: { dealValue: { $gt: 0 } } },
{ $group: { _id: '$status', total: { $sum: '$dealValue' }, deals: { $sum: 1 } } },
{ $sort: { total: -1 } },
])
.toArray();
console.log(byStatus);
// How many clients per status
const counts = await clients.aggregate([{ $sortByCount: '$status' }]).toArray();
console.log(counts);

$match, $project, $addFields / $set, $unset, $group, $sort, $skip, $limit, $count, $unwind, $lookup, $sortByCount, and other read-only stages.

$out and $merge aren’t available: write results with insertMany or bulkWrite instead.

Pipelines support MongoDB’s expression operators: arithmetic ($add, $multiply, $round…), comparison, conditional ($cond, $ifNull, $switch), string ($concat, $toUpper, $substrCP…), array ($size, $filter, $map…), date ($year, $dateToString… on date fields stored as ISO strings, convert with $toDate) and accumulators ($sum, $avg, $min, $max, $push, $addToSet, $first, $last). See the operator reference.

JavaScript in pipelines ($where, $function, $accumulator) is never run.

A pipeline has at most 50 stages and works on the whole collection in memory, which is fast for the database sizes the app supports (tens of thousands of records).

Made by Faeiz Furqan