Mingo
MongoDB query language for in-memory objects
README
mingo
MongoDB query language for in-memory objects
Install
$ npm install mingo
Features
- Query and Projection Operators.
For documentation on using operators see mongodb
Browse package docs for modules.
Usage
- ```js
- // Use as es6 module
- import mingo from "mingo";
- // or vanilla nodeJS
- const mingo = require("mingo");
- ```
The main module exports Aggregator, Query, aggregate(), find(), and remove(). Only Query and Projection operators are loaded by default when you require the main module. This is done using the side-effect modulemingo/init/basic and automatically includes pipeline operators; $project, $skip, $limit, and $sort.
Loading Operators
MongoDB query library is huge and you may not need all the operators. If using this library on the server-side where bundle size is not a concern, you can load all operators as shown below.
- ```js
- // Note that doing this effectively imports the entire library into your bundle and unused operators cannot be tree shaked
- import "mingo/init/system";
- ```
Or from the node CLI
- ```sh
- node -r 'mingo/init/system' myscript.js
- ```
To support tree-shaking for client side bundles, you can import and register specific operators that will be used in your application.
ES6
- ```js
- import { useOperators, OperatorType } from "mingo/core";
- import { $trunc } from "mingo/operators/expression";
- import { $bucket } from "mingo/operators/pipeline";
- useOperators(OperatorType.EXPRESSION, { $trunc });
- useOperators(OperatorType.PIPELINE, { $bucket });
- ```
CommonJS
- ```js
- const core = require("mingo/core");
- const $trunc = require("mingo/operators/expression").$trunc;
- const $bucket = require("mingo/operators/pipeline").$bucket;
- const useOperators = core.useOperators;
- const OperatorType = core.OperatorType;
- useOperators(OperatorType.EXPRESSION, { $trunc: $trunc });
- useOperators(OperatorType.PIPELINE, { $bucket: $bucket });
- ```
Using query to test objects
- ```js
- import { Query } from "mingo";
- // create a query with criteria
- // find all grades for homework with score >= 50
- let query = new Query({
- type: "homework",
- score: { $gte: 50 }
- });
- // test if an object matches query
- query.test(doc);
- ```
Searching and Filtering
- ```js
- import { Query } from "mingo";
- // input is either an Array or any iterable source (i.e Object{next:Function}) including ES6 generators.
- let criteria = { score: { $gt: 10 } };
- let query = new Query(criteria);
- // filter collection with find()
- let cursor = query.find(collection);
- // alternatively use shorthand
- // cursor = mingo.find(collection, criteria)
- // sort, skip and limit by chaining
- cursor.sort({ student_id: 1, score: -1 }).skip(100).limit(100);
- // count matches. exhausts cursor
- cursor.count();
- // classic cursor iterator (old school)
- while (cursor.hasNext()) {
- console.log(cursor.next());
- }
- // ES6 iterators (new cool)
- for (let value of cursor) {
- console.log(value);
- }
- // all() to retrieve matched objects. exhausts cursor
- cursor.all();
- ```
Using $jsonSchema operator
To use the $jsonSchema operator, you must register your own JsonSchemaValidator in the options.
No default implementation is provided out of the box so users can use a library with their preferred schema format.
The example below uses Ajv to implement schema validation.
- ```js
- import { RawObject } from "mingo/types"
- import { JsonSchemaValidator } from "mingo/core"
- import Ajv, { Schema } from "ajv"
- const jsonSchemaValidator: JsonSchemaValidator = (s: RawObject) => {
- const ajv = new Ajv();
- const v = ajv.compile(s as Schema);
- return (o: RawObject) => (v(o) ? true : false);
- };
- const schema = {
- type: "object",
- required: ["item", "qty", "instock"],
- properties: {
- item: { type: "string" },
- qty: { type: "integer" },
- size: {
- type: "object",
- required: ["uom"],
- properties: {
- uom: { type: "string" },
- h: { type: "number" },
- w: { type: "number" },
- },
- },
- instock: { type: "boolean" },
- },
- };
- // queries documents using schema validation
- find(docs, { $jsonSchema: schema }, {}, { jsonSchemaValidator }).all();
- ```
Note: An error is thrown when the $jsonSchema operator is used without a the jsonSchemaValidator configured.
Aggregation Pipeline
- ```js
- import { Aggregator } from "mingo/aggregator";
- import { useOperators, OperatorType } from "mingo/core";
- import { $match, $group } from "mingo/operators/pipeline";
- import { $min } from "mingo/operators/accumulator";
- // ensure the required operators are preloaded prior to using them.
- useOperators(OperatorType.PIPELINE, { $match, $group });
- useOperators(OperatorType.ACCUMULATOR, { $min });
- let agg = new Aggregator([
- { $match: { type: "homework" } },
- { $group: { _id: "$student_id", score: { $min: "$score" } } },
- { $sort: { _id: 1, score: 1 } }
- ]);
- // return an iterator for streaming results
- let stream = agg.stream(collection);
- // return all results. same as `stream.all()`
- let result = agg.run(collection);
- ```