ts-mongo-aggregation-parser

TS Parser for Mongo pipeline aggregation queries

Stars
2

ts-mongo-aggregation-parser

This parser is generated using pegjs. It parses a string containing a MongoDB aggregation pipeline and returns an AST. The AST Types are defined in src/ast-types.ts. This package is compatible with CommonJS and ESM.

Motivations

Allow Maggregor to parse request pipelines on MongoDB. Maggregor is a simple data-layer that speeds up MongoDB queries: https://github.com/maggregor/maggregor

Installation

npm install ts-mongo-aggregation-parser
yarn add ts-mongo-aggregation-parser
pnpm add ts-mongo-aggregation-parser

Parser usage

import { astTypes, parse } from 'ts-mongo-aggregation-parser'

const pipeline = `[
{
  $group: {
    _id: '$name',
    count: {
      $sum: 1,
    },
  },
},
]`

const ast = parse(pipeline)

Using the AST Visitor

The Visitor AST provides a good way to traverse and manipulate our custom Abstract Syntax Trees (ASTs). To use the AST visitor, simply extend the BaseASTVisitor class and override the methods for the specific AST node types you're interested in. Below is a brief example:

import {
	ASTAggregationExpression,
	ASTField,
	ASTProperty,
	ASTStageGroup,
	ASTStageList,
	ASTVisitor,
	BaseASTVisitor,
} from './ts-mongo-aggregation-parser'

class CustomASTVisitor extends BaseASTVisitor {
	visitStageGroup(stageGroup: ASTStageGroup): void {
		console.log(`StageGroup ID: ${stageGroup.id.name}`)
	}

	visitAggregationExpression(agg: ASTAggregationExpression): void {
		console.log(`Aggregation Operator: ${agg.operator}`)
	}
}

// Assuming you have created an AST
const ast = new ASTStageList() /* your stages here */

// Use your custom visitor
const visitor = new CustomASTVisitor()
ast.accept(visitor)

Supported aggregation operators

  • $sum
  • $avg
  • $max
  • $min
  • $push
  • $addToSet
  • $first
  • $last
  • $addToSet

Supported stages

  • $group
  • $project
  • $match
  • $limit
  • $skip
  • $unwind
  • $sort