npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongo-db-aggregator

v1.2.3

Published

Chainable MongoDB aggregation builder for Node.js and Mongoose

Readme

Mongo Aggregation Builder

A chainable, intuitive builder for creating MongoDB aggregation pipelines. Build dynamic and readable pipelines using classes and fluent syntax.


📦 Installation

npm install mongo-db-aggregator

or

yarn add mongo-db-aggregator

🚀 Features

  • Fluent API for all major aggregation stages
  • Modular Builders for $match, $project, $group, $sort, $lookup, $facet, and more.
  • Embedded operator support ($map, $filter, $cond, etc.) -Designed to work seamlessly with mongoose or native mongodb driver

Examples

const { aggregator } = require('mongo-db-aggregator');
const mongoose = require('mongoose');

const schema = new mongoose.Schema({}, { strict: false });
const Model = mongoose.model('Client', schema, 'clients');

const data = await aggregator(Model, AggregationOptions)
  .match({ companyName: "PBADGE" })
  .project(new ProjectBuilder().add('companyName', 1).add('_id', 0).done())
  .limit(1)
  .exec();

console.log(data);

Lookup with Projection Pipeline

const data = await aggregator(Model, AggregationOptions)
  .lookup(
    new LookupBuilder()
      .from('clients')
      .as('client')
      .localField('client')
      .foreignField('_id')
      .pipeline([
        { $project: new ProjectBuilder().add('companyName', 1).done() }
      ])
      .done()
  )
  .unwind(new UnwindBuilder().path('$client').done())
  .exec();

Using Operators (e.g., $map, $filter, $cond)

const data = await aggregator(Model, AggregationOptions)
  .project(
    new ProjectBuilder().add('score',
      new $Map()
        .input('$$approvalTracking')
        .as('track')
        .in(1)
        .done()
    ).add('statusLabel',
      new $Cond()
        .if({ $eq: ["$status", "active"] })
        .then("Active")
        .else("Inactive")
        .done()
    ).done()
  )
  .exec();

Pagination Made Simple

const [result] = await aggregator(Model, AggregationOptions)
    .paginate({ page: 1, perPage: 5 })
    .exec();

Create Macros For Reuseability

const {aggregator, AggregatorClass} = require('./dist');

AggregatorClass.registerMacro('customProject', () => {
  return new ProjectStage(
      new ProjectBuilder().add('working', true),
  ).build();
});

AggregatorClass.registerMacro('customMatchAndSort', () => {
  return [
    new MatchStage({}).build(),
    new SortStage({
      createdAt: -1
    }).build(),
    new ProjectStage(
        new ProjectBuilder().add("companyName", 1)
    ).build()
  ];
});

const [result] = await aggregator(Model).useMacro('customMatchAndSort').
    limit(1).exec();

Using condition


const result = await aggregator(Model).
    match({isActive: true}).
    cond(true, b => b.match({role: 'admin'})).
    exec();

const result = await aggregator(Model).
    match({isActive: true}).
    cond(false, b => b.match({role: 'admin'})).
    exec();

const result = await aggregator(Model)
.cond(() => true, b => b.limit(5)).exec();

const result = await 
    aggregator(Model).cond(() => false, b => b.limit(5)).exec();

Nested Condition


const result = await aggregator(Model)
.cond(
    true,
    (agg) => 
        agg.cond(true, (nestAgg) => nestAgg.match({isActive: true})
    )
)

Macros With Arguments

AggregatorClass.registerMacro("macroWithArgs", (userId, userNewId) => {
      return [
          new MatchStage({
            id: userId,
            newUserId: userNewId
          }).build()
      ]
    })

    const result =
        aggregator(Model)
        .useMacro("macroWithArgs", 5, 6)
            .toJSON()

📚 API Overview

Builders

  • ProjectBuilder
  • GroupBuilder
  • LookupBuilder
  • UnwindBuilder
  • FacetBuilder
  • UnionWithBuilder
  • (More to Come soon)

Stages

  • AddFields
  • MatchStage
  • ProjectStage
  • GroupStage
  • SortStage
  • LimitStage
  • LookupStage
  • UnwindStage
  • FacetStage
  • UnionWithStage
  • (More to Come soon)

Operators

  • $Map
  • $Filter
  • $Cond
  • $Reduce
  • $Switch
  • (More to Come soon)

Stage Helpers

  • dateRange

🧠 Inspiration

Inspired by the repetitive nature of writing MongoDB pipelines manually and the desire for a more readable, chainable syntax in JavaScript.

📄 License

MIT License