mongo-typed
TypeScript utility types for building strongly-typed MongoDB filters, updates, and aggregation pipelines — without adding dependencies.
Overview
mongo-typed provides type-safe MongoDB-style query, update, and aggregation utilities in TypeScript. It is designed to assist with building fully-typed data layers or services that interact with MongoDB-like syntax, without relying on external libraries or runtime packages.
Whether you're working with an actual MongoDB database or implementing similar patterns in your application logic, mongo-typed gives you strong typing for common Mongo operations like filters, updates, and aggregation pipelines.
Features
- Fully typed filter support (including
$and, $or, $in, $elemMatch, etc.)
- Strongly typed update operations (e.g.,
$set, $inc, $unset, etc.)
- Fluent aggregation pipeline builder with schema tracking across stages
- Fluent find and findById builders with type-safe projections
- No dependencies — pure TypeScript
- Helps catch invalid Mongo-like queries at compile time
Installation
pnpm add mongo-typed
# or
npm install mongo-typed
# or
yarn add mongo-typed
Usage
Filter
import { Filter } from 'mongo-typed';
type User = {
_id: string;
email: string;
age: number;
roles: string[];
};
const query: Filter<User> = {
age: { $gte: 18 },
roles: { $in: ['admin', 'user'] },
$or: [
{ email: /@example\.com$/ },
{ email: { $exists: false } }
]
};
Update
import { Update } from 'mongo-typed';
const update: Update<User> = {
$set: {
email: 'new@email.com'
},
$inc: {
age: 1
},
$unset: {
roles: true
}
};
Aggregation Pipeline
The pipeline() function returns a fluent builder that tracks the document schema as it flows through each stage. The output type updates automatically — $group reshapes the schema, $unwind flattens arrays, $project picks or excludes fields, and so on.
import { pipeline } from 'mongo-typed';
type User = {
_id: string;
department: string;
salary: number;
active: boolean;
};
const stages = pipeline<User>()
.match({ active: true })
.group({ _id: '$department', headcount: { $sum: 1 } })
.sort({ headcount: -1 })
.build();
// stages: [{ $match: ... }, { $group: ... }, { $sort: ... }]
Supported stages: $addFields, $count, $facet, $group, $limit, $lookup, $match, $merge, $out, $project, $replaceRoot, $replaceWith, $sample, $set, $setWindowFields, $skip, $sort, $sortByCount, $unset, $unwind.
Find Builder
FindBuilder provides a fluent, type-safe interface for MongoDB find queries. It tracks the document schema through projections — select() reshapes the output type while where() and sort() validate against the input schema.
import { FindBuilder, FindOptions } from 'mongo-typed';
type User = {
_id: string;
name: string;
email: string;
age: number;
active: boolean;
};
// Subclass to connect to your database
class MyFind<TInput extends object, TOutput extends object = TInput>
extends FindBuilder<TInput, TOutput, MyFindTerminal> implements MyFindTerminal {
constructor(private collection: Collection, options?: FindOptions) { super(options); }
protected override create<T extends object, U extends object>(options: FindOptions) {
return new MyFind<T, U>(this.collection as any, options);
}
async toArray(): Promise<TOutput[]> {
return this.collection.find(this.options.filter ?? {}, this.options).toArray() as any;
}
build() { return { ...this.options }; }
}
Available methods: where, select, sort, limit, skip, collation, hint.
FindById Builder
FindByIdBuilder is a restricted builder for single-document lookups by _id. Only select() and hint() are available — no where, sort, limit, or skip.
import { FindByIdBuilder } from 'mongo-typed';
// Subclass similarly to FindBuilder
class MyFindById<TInput extends object, TOutput extends object = TInput>
extends FindByIdBuilder<TInput, TOutput, MyFindByIdTerminal> implements MyFindByIdTerminal {
constructor(private collection: Collection, options?: FindOptions) { super(options); }
protected override create<T extends object, U extends object>(options: FindOptions) {
return new MyFindById<T, U>(this.collection as any, options);
}
async toObject(): Promise<TOutput | null> {
return this.collection.findOne(this.options.filter ?? {}, this.options) as any;
}
build() { return { ...this.options }; }
}
// Usage in a data layer
class UserStore {
find(filter?: Filter<User>) {
return new MyFind<User>(this.collection, filter ? { filter } : {});
}
findById(id: string) {
return new MyFindById<User>(this.collection, { filter: { _id: id } });
}
}
// repo.find({ active: true }).select({ name: 1, email: 1 }).sort({ name: 1 }).limit(10).toArray()
// repo.findById('abc').select({ name: 1 }).toObject()
Update Pipeline
MongoDB allows updates to use an aggregation pipeline instead of traditional operators. The updatePipeline() builder restricts the available stages to only the ones valid in updates: $addFields, $set, $project, $unset, $replaceRoot, $replaceWith.
import { updatePipeline } from 'mongo-typed';
const stages = updatePipeline<User>()
.set({ fullName: { $concat: ['$firstName', ' ', '$lastName'] } })
.unset('firstName')
.build();
// Pass to collection.updateMany(filter, stages)
Extending the builder
PipelineBuilder is a generic base class that can be extended for custom terminal behavior. The second type parameter TTerminal controls what terminal methods (like $merge and $out) return:
import { PipelineBuilder } from 'mongo-typed';
interface MyTerminal {
execute: () => Promise<object[]>;
}
class MyPipeline<T extends object> extends PipelineBuilder<T, MyTerminal> implements MyTerminal {
async execute() {
// run the pipeline against your database
return this.stages;
}
protected override create<U extends object>(stages: object[]) {
return new MyPipeline<U>(stages);
}
}
Clauses (2.0)
Beside the types, 2.0 reads Mongo clauses at run time: a filter, an update (operators or a pipeline), a projection, an
aggregation expression or a document is parsed into a typed tree, as mongod 8.0 reads it. Queries ask what a tree
reads, writes or pins; transforms map its values and give back a tree that serialises exactly as given where
untouched. The operator tables are MongoDB 8.0's documented ones, checked against mongod 8.0.17 (MONGODB_VERSION).
Parsing
import { parseDocument, parseExpression, parseFilter, parseProjection, parseUpdate, serialize } from 'mongo-typed';
const filter = parseFilter({ status: 'open', 'lines.qty': { $gt: 1 } });
const update = parseUpdate({ $set: { 'lines.$[l].qty': 2 } }, { arrayFilters: [{ 'l.sku': 'a' }] });
const pipeline = parseUpdate([{ $set: { total: { $sum: '$lines.qty' } } }]);
const projection = parseProjection({ name: 1, lines: { $slice: 2 } });
const expression = parseExpression({ $add: ['$total', 1] });
const document = parseDocument({ _id: 'x', lines: [{ qty: 1 }] });
serialize(filter); // { status: 'open', 'lines.qty': { $gt: 1 } }, exactly as given
Every parser takes ParseOptions: resolve, a reader of path segments by a schema (see modelClauses), and
variables, the names an expression may read beside the system ones (what a $lookup's let binds). Some take more:
parseFilter(raw, { outerDepth }) and parseExpression(raw, { outerDepth }): how many levels sit above the clause,
so the depth mongod refuses at is the one the parse refuses at. Alone, an expression counts itself below the one
field it computes.
parseUpdate(raw, { arrayFilters, upsert }): with upsert, the row the update may insert is held to a document's
depth (UpdateParseOptions). {} is refused: mongod reads it as a replacement, the row replaced with an empty one.
parseProjection(raw, { grammar: 'aggregation' }) reads a $project stage's projection; the default is a find's.
parseArrayFilters(raw) reads an update's arrayFilters on their own, with every refusal that needs no statement
(each an object with one valid, distinct identifier, of the array-filter grammar, within its depth; a null or undefined one
passed over, as mongod does, a skipped entry in its place). serializeArrayFilters(entries) writes the list back
exactly, nulls and undefineds where they were. An identifier
no filter defines, or a filter no path uses, needs the statement: parseUpdate refuses those.
A parse refuses what mongod refuses, and more by decision: an object mixing operators with fields, __proto__,
constructor and prototype keys and segments, $-prefixed segments and value keys outside a DBRef, positional
segments outside an update, and unknown operators. canonical(tree) rebuilds a tree from its parts; and() and or()
fold filters, refusing a fold mongod's planner would refuse.
Queries
fieldConditions(filter), conditionLeaves(filter), comparisons(filter, match?, { expand }), filterReads(filter),
opaqueNodes(filter): what a filter names, compares and reads, $expr and $elemMatch included.
equalityPins(filter, mode) and pinnedId(filter): what a filter pins its paths to: the row an upsert seeds
(mongoSeed), what every matched row holds (everyRow), or top-level equalities (topLevel).
writes(update) and storedValues(update, { expand }): every path an update writes, and every value it stores there,
pipeline constants included, each expression with what it reads. A whole-row stage writes an empty path.
projectionReads(projection): each field a projection computes (an expression, not a constant), and what it reads.
reads(expression): the paths an expression reads (and of those, shapeOnlyPaths, asked only their size,
whether a list, or their type: still read, as a size or a type tells something, but no field below them), the reads
of variables it binds itself (through: the variable, the stored path it stands for or undefined for a computed
value, the path read below it; precision on top of paths, which already holds what such a read reaches, never
needed for soundness), isByName (a field read by a name held as data:
$getField, $setField, $unsetField, $objectToArray, $arrayToObject, a $sortArray by fields, a script),
isRebound and
isUncheckable (whether it may read a field it names only when it runs: a script, a computed or dotted $getField
name, a rebound system variable, a variable bound outside it; a $getField of a plain name is checkable).
filterReads carries the three flags for a filter's $exprs.
documentValues(document) and valuesAt(value, at, match): the values a document or a stored value holds, by path.
pathMatcher(paths, { relation }): matches paths field by field, positions and indexes left out, by exact (the
default), within, covers or overlaps.
Transforms
mapValues(tree, match, map, options?) and mapValuesAsync(...) replace each value at a path match matches: a
filter's operands (its $expr constants with { expr: true }), an update's stored values and every constant a pipeline
stores, a document's values. A mapped value goes back as a constant, wrapped in $literal where it would read as an
expression; a mapping that would change an operator's meaning (a value turned into a pattern) is refused. A transform
matches by exact or within only, and visits a node a value shares once per place it sits.
Structural transforms
These change a tree's shape: parse once, change the tree, serialize once. Each is pure: it gives back a new tree,
sharing every node it leaves alone, or the tree it was given when nothing changes. A clause or entry a transform adds
is parsed where it lands, read as the tree was (its schema, its variables, its depth); what the change can break
besides is checked (two clauses on one key, a conflict between update paths, the array filters' use, the planner's
rules, the depth a wrap adds), with the ClauseError the parse would give; what it leaves alone is never read again,
and serialises exactly as given. A refusal the library makes of its own, where mongod would take the result but it
isn't what the transform was asked for, is TransformRefused. A tree made of several (and(), or(), a merge or
narrowing of projections) is read as they all were where they agree; where they don't, without a schema, with every
variable any binds, and as deep as the deepest sits.
import { flatten, mapPaths, mergeProjections, moveEntry, narrowProjection, parseFilter, parseProjection, parseUpdate, pathMatcher, projectionOf, removeEntries, removeFromProjection, replaceClauses, serialize, setEntry, split, withoutOperator } from 'mongo-typed';
const filter = parseFilter({ $and: [{ owner: 'u1' }, { status: 'open' }], $or: [{ owner: 'u2' }, { total: 1 }] });
// Rename every path the tree reads or writes by prefix; `from: ''` prefixes the whole row.
serialize(mapPaths(filter, [{ from: '', to: 'doc' }])); // { $and: [{ 'doc.owner': 'u1' }, { 'doc.status': 'open' }], $or: [{ 'doc.owner': 'u2' }, { 'doc.total': 1 }] }
// Replace or drop field clauses, through logical arms and $elemMatch. An arm left empty drops out of $and, drops the
// whole $or (an empty arm matches every row), and is refused in $nor.
serialize(replaceClauses(filter, pathMatcher(['status']), () => null)); // { $and: [{ owner: 'u1' }], $or: […] }
// Split in two: only top-level and $and clauses move; an $or or $nor naming a claimed clause stays whole in rest, in held.
const { held, matched, rest } = split(filter, clause => clause.kind === 'field' && clause.path.raw === 'owner');
// matched: { owner: 'u1' }; rest: { $and: [{ status: 'open' }], $or: [{ owner: 'u2' }, { total: 1 }] }; held: [the $or]
serialize(flatten(parseFilter({ $and: [{ a: 1 }, { b: 1 }], c: 1 }))); // { c: 1, a: 1, b: 1 }
serialize(withoutOperator(parseFilter({ a: 1, $comment: 'x' }), ['$comment', '$text'])); // { a: 1 }
const update = parseUpdate({ $inc: { n: 1 }, $set: { a: 1, 'xs.$[e].v': 2 } }, { arrayFilters: [{ 'e.k': 1 }] });
serialize(setEntry(update, { op: '$set', path: 'b', value: 2 })); // { $inc: { n: 1 }, $set: { a: 1, 'xs.$[e].v': 2, b: 2 } }
serialize(removeEntries(update, pathMatcher(['xs'], { relation: 'within' }))!); // { $inc: { n: 1 }, $set: { a: 1 } }, its array filter dropped
serialize(moveEntry(update, { op: '$set', path: 'a' }, '$setOnInsert')); // { $inc: …, $set: { 'xs.$[e].v': 2 }, $setOnInsert: { a: 1 } }
serialize(withoutOperator(update, '$inc')!); // an update's operators, or a pipeline's stages; undefined where none would be left
serialize(mergeProjections(parseProjection({ a: 1 }), parseProjection({ _id: 0, b: 1 }))); // { a: 1, b: 1 }: what either shows
serialize(narrowProjection(parseProjection({ a: 1, 'b.c': 1 }), parseProjection({ b: 1 }))); // { 'b.c': 1 }: what both show
serialize(removeFromProjection(parseProjection({ a: 1, b: 1 }), ['b', '_id'])); // { _id: 0, a: 1 }
serialize(projectionOf(['a', 'a.b', 'c'])); // { a: 1, c: 1 }