MongoDB Aggregate Pipeline Build

Build MongoDB aggregation pipelines with typed stages for filtering grouping and projection.

JavascriptData Fetching

Code

javascriptsnippet
1 line
import{MongoClient}from'mongodb';export function aggregateBuilder(collection){const stages=[];const api={$match:(q)=>{stages.push({$match:q});return api;},$group:(g)=>{stages.push({$group:g});return api;},$sort:(s)=>{stages.push({$sort:s});return api;},$project:(p)=>{stages.push({$project:p});return api;},$limit:(n)=>{stages.push({$limit:n});return api;},$lookup:(l)=>{stages.push({$lookup:l});return api;},exec:async()=>collection.aggregate(stages).toArray()};return api;}export async function connect(url){const client=new MongoClient(url);await client.connect();return client.db();}

What the code does

Everything happens inside the functions aggregateBuilder and connect.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Reach for mongodb and what you get is MongoClient — that is the whole API contact area.

Caveats

  • External dependency: mongodb — install it before running the snippet.

Where you would use it

The primary signature is export function aggregateBuilder(collection)

aggregateBuilder is the public entry point; everything else in the file exists to support it.

FAQ

Are there third-party dependencies?
`mongodb` — install it with the package manager before running.