mongo-query-compiler

raw JSON →
1.0.7 verified Fri May 01 auth: no javascript

Converts MongoDB query objects into optimized JavaScript filter functions for in-memory array filtering. Version 1.0.7 is stable with no active development since 2021. Differentiates from lodash's _.filter by supporting MongoDB query operators like $regex, $geoWithin, and $elemMatch. Lightweight, no dependencies, works in browser and Node.js.

error TypeError: Illegal invocation
cause The compiled function uses this internally but is not bound to an object.
fix
Bind the filter function to the array if needed, or just pass to .filter() directly.
error SyntaxError: Unexpected token $
cause Using a query operator like $regex as a field name directly.
fix
Wrap it in an object: { field: { $regex: 'pattern' } }
gotcha Query keys with dots are treated as nested field paths, not literal property names.
fix Use literal keys with $literal or avoid dots in field names.
breaking In version 1.0.0, the default import changed from compile to compileQuery.
fix Update imports to use compileQuery as default.
deprecated The $where operator is deprecated in favor of JavaScript function maps.
fix Use the expression parameter to pass custom functions.
npm install mongo-query-compiler
yarn add mongo-query-compiler
pnpm add mongo-query-compiler

Compiles a MongoDB query into a filter function and applies it to an array.

import compileQuery from 'mongo-query-compiler';
const filter = compileQuery({ age: { $gte: 18 } });
const data = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 17 }
];
const adults = data.filter(filter);
console.log(adults); // [{ name: 'Alice', age: 25 }]