mingo
JavaScript implementation of MongoDB query language
Last updated 8 years ago by kofrasa .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install mingo 
SYNC missed versions from official npm registry.

mingo

MongoDB query language for in-memory objects

license version build issues codecov npm downloads

Install

$ npm install mingo

Features

For more documentation on how to use operators see mongodb.

Browse package docs for modules.

Usage

// 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 module mingo/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.

// 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

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

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

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

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

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.

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

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);

Options

Query and aggregation operations can be configured with options to enabled different features or customize how documents are processed. Some options are only relevant to specific operators and need not be specified if not required.

Name Description Default Behaviour
idKey The key that is used to lookup the ID value of a document. "_id"
collation Collation specification for string sorting operations. none See Intl.Collator
processingMode Determines copy rules for inputs and outputs. CLONE_OFF Turn off cloning and modifies the input collection as needed.
This option will also return output objects with shared paths in their graph when specific operators are used. Provides the greatest speedup by minizing cloning. When using the aggregation pipeline, you can use the $out operator to collect immutable intermediate results.
useStrictMode Enforces strict MongoDB compatibilty. true When disabled, behaviour changes as follows.
  • $elemMatch returns all matching nested documents instead of only the first.
  • Empty string "" is coerced to false during boolean checking in supported operators which is consistent with Javascript semantics.
    scriptEnabled Enable or disable using custom script execution. true When disabled, operators that execute custom code are disallowed such as; $where, $accumulator, and $function.
    hashFunction Custom hash function to replace the default based on "Effective Java" hashCode. default Expects function (value: unknown) => number.
    collectionResolver Function to resolve strings to arrays for use with operators that reference other collections such as; $lookup, $out and $merge. none Expects function (name: string) => RawObject[]
    jsonSchemaValidator JSON schema validator to use for the $jsonSchema operator. none Expects function (schema: RawObject) => (document: RawObject) => boolean.
    The $jsonSchema operation would fail if a validator is not provided.
    variables Global variables to pass to all operators none
    context Container to use for loading operators. none This option allow users to load only desired operators or register custom operators which need not be available globally.
    useGlobalContext Allow falling back to the global context when operator is not found in the provided context. true This is provided to allow users to strictly enforce which operators may be usable.

    Adding Custom Operators

    Custom operators can be registered using Context via the context option which is the recommended way from 6.4.2. The Context is a container for operators, that the execution engine will use to process queries. Previously, the useOperators(...) function was used to register operators globally but that is no longer preferred. The difference between the two is that a globally registered operator cannot be overwritten whereas a new context may be created and used at anytime.

    NB: Note that the execution engine will first try to find the operator in the context and fallback to the global context when not found.

    Each operator type has a specific interface to which an implementation must conform to be valid.

    Pre-loaded operators defined here cannot be overridden. These include;

    NB: Update operators is not supported in Context.

    Updating Documents

    An update operation can be performed using the updateObject function from the mingo/updater module. Unlike other operations in the library, this only works on a single object. The query and aggregation operators are powerful enough to use for transforming arrays of documents and should be preferred when dealing with multiple objects. updateObject returns an array of all paths that were updated. It also supports arrayFilters for applicable operators. To detect whether a change occured you can check the length of the returned array.

    All operators as of MongoDB 5.0 are supported except the positional array operator $.

    Examples

    import { updateObject } from "mingo/updater";
    // all update operators are automatically loaded.
    
    const obj = {
      firstName: "John",
      lastName: "Wick",
      age: 40,
      friends: ["Scooby", "Shagy", "Fred"]
    };
    
    // returns array of modified paths if value changed.
    updateObject(obj, { $set: { firstName: "Bob", lastName: "Doe" } }); // ["firstName", "lastName"]
    
    // update nested values.
    updateObject(obj, { $pop: { friends: 1 } }); // ["friends"] => friends: ["Scooby", "Shagy"]
    // update nested value path
    updateObject(obj, { $unset: { "friends.1": "" } }); // ["friends.1"] => friends: ["Scooby", null]
    // update with condition
    updateObject(obj, { $set: { "friends.$[e]": "Velma" } }, [{ e: null }]); // ["friends"] => friends: ["Scooby", "Velma"]
    // empty array returned if value has not changed.
    updateObject(obj, { $set: { fristName: "Bob" } }); // [] => no change to object.
    

    You can also create a preconfigured updater function.

    import { createUpdater } from "mingo/updater";
    
    // configure updater to deep clone passed values. clone mode defaults to "copy".
    const updateObject = createUpdater({ cloneMode: "deep" });
    
    const state = { people: ["Fred", "John"] };
    const newPeople = ["Amy", "Mark"];
    
    console.log(state.people); // ["Fred", "John"]
    
    updateObject(state, { $set: { people: newPeople } });
    
    newPeople.push("Jason");
    
    console.log(state.people); // ["Amy", "Mark"]
    console.log(newPeople); // ["Amy", "Mark", "Jason"]
    

    Differences from MongoDB

    This list describes how this library differs from the full MongoDB query engine.

    1. There is no concept of a collection. Input data is either an array of objects or a generator function to support streaming.
    2. Does not support server specific operators. E.g. $collStat, $planCacheStats, $listSessions.
    3. Does not support geometry query operators. no support planned.
    4. Does not support query operators dependent on persistent storage; $comment, $meta, $text.
    5. Does not support positional query or update operator $.
    6. Does not support server specific expression operators; $toObjectId, $binarySize, bsonSize.
    7. Agregation pipeline operator $merge enforces unique constraint on the lookup field at runtime.
    8. Custom function evaluation operators; $where, $function, and $accumulator, do not accept strings as the function body.
    9. Custom function evaluation operators are enabled by default. They can be disabled with the scriptEnabled option.
    10. Custom function evaluation operator $accumulator does not support the merge option.
    11. The $jsonSchema operator requires the user to register their own validator using the jsonSchemaValidator configuration.

    Benefits

    • Declarative data driven API.
    • Usable on both frontend and backend.
    • Provides an alternative to writing custom code for transforming objects.
    • Validate MongoDB queries without running a server.
    • Well documented. MongoDB query language is among the best available and has great documentation.

    Contributing

    • Squash changes into one commit.
    • Run npm test to build and run unit tests.
    • Submit pull request.

    To validate correct behaviour and semantics of operators, you may also test against mongoplayground.net. Credit to the author.

    A big thank you to all users and CONTRIBUTORS of this library.

    License

    MIT

    Current Tags

    • 6.4.15                                ...           latest (7 months ago)

    140 Versions

    • 6.4.15                                ...           7 months ago
    • 6.4.14 [deprecated]           ...           7 months ago
    • 6.4.13                                ...           8 months ago
    • 6.4.12                                ...           9 months ago
    • 6.4.11 [deprecated]           ...           9 months ago
    • 6.4.10                                ...           a year ago
    • 6.4.9                                ...           a year ago
    • 6.4.8                                ...           a year ago
    • 6.4.7                                ...           a year ago
    • 6.4.6                                ...           a year ago
    • 6.4.5                                ...           a year ago
    • 6.4.4                                ...           a year ago
    • 6.4.3                                ...           a year ago
    • 6.4.2                                ...           a year ago
    • 6.4.1                                ...           a year ago
    • 6.4.0                                ...           a year ago
    • 6.3.4                                ...           a year ago
    • 6.3.3 [deprecated]           ...           a year ago
    • 6.3.2                                ...           2 years ago
    • 6.3.1                                ...           2 years ago
    • 6.3.0                                ...           2 years ago
    • 6.2.7                                ...           2 years ago
    • 6.2.6 [deprecated]           ...           2 years ago
    • 6.2.5                                ...           2 years ago
    • 6.2.4                                ...           2 years ago
    • 6.2.3                                ...           2 years ago
    • 6.2.2 [deprecated]           ...           2 years ago
    • 6.2.1                                ...           2 years ago
    • 6.2.0                                ...           2 years ago
    • 6.1.3                                ...           2 years ago
    • 6.1.2                                ...           2 years ago
    • 6.1.1                                ...           2 years ago
    • 6.1.0                                ...           2 years ago
    • 6.0.6                                ...           3 years ago
    • 6.0.5                                ...           3 years ago
    • 6.0.4                                ...           3 years ago
    • 6.0.3                                ...           3 years ago
    • 6.0.2                                ...           3 years ago
    • 6.0.1                                ...           3 years ago
    • 6.0.0                                ...           3 years ago
    • 5.1.0                                ...           3 years ago
    • 5.0.0                                ...           3 years ago
    • 4.4.1                                ...           3 years ago
    • 4.4.0                                ...           3 years ago
    • 4.3.0                                ...           3 years ago
    • 4.2.0                                ...           3 years ago
    • 4.1.5                                ...           3 years ago
    • 4.1.4                                ...           3 years ago
    • 4.1.3                                ...           3 years ago
    • 4.1.2                                ...           4 years ago
    • 4.1.1                                ...           4 years ago
    • 4.1.0                                ...           4 years ago
    • 4.0.0                                ...           4 years ago
    • 3.1.0                                ...           4 years ago
    • 3.0.6                                ...           4 years ago
    • 3.0.5                                ...           4 years ago
    • 3.0.4                                ...           4 years ago
    • 3.0.3                                ...           4 years ago
    • 3.0.2                                ...           4 years ago
    • 3.0.1                                ...           5 years ago
    • 3.0.0                                ...           5 years ago
    • 2.5.3                                ...           5 years ago
    • 2.5.2                                ...           5 years ago
    • 2.5.1 [deprecated]           ...           5 years ago
    • 2.5.0                                ...           5 years ago
    • 2.4.0                                ...           5 years ago
    • 2.3.6                                ...           5 years ago
    • 2.3.5                                ...           6 years ago
    • 2.3.4                                ...           6 years ago
    • 2.3.3                                ...           6 years ago
    • 2.3.2                                ...           6 years ago
    • 2.3.1                                ...           6 years ago
    • 2.3.0                                ...           6 years ago
    • 2.2.12                                ...           6 years ago
    • 2.2.11                                ...           6 years ago
    • 2.2.10                                ...           6 years ago
    • 2.2.9                                ...           6 years ago
    • 2.2.8                                ...           6 years ago
    • 2.2.7                                ...           6 years ago
    • 2.2.6                                ...           6 years ago
    • 2.2.5                                ...           6 years ago
    • 2.2.4                                ...           6 years ago
    • 2.2.3                                ...           6 years ago
    • 2.2.2                                ...           7 years ago
    • 2.2.1                                ...           7 years ago
    • 2.2.0                                ...           7 years ago
    • 2.1.1                                ...           7 years ago
    • 2.1.0                                ...           7 years ago
    • 2.0.5                                ...           7 years ago
    • 2.0.4                                ...           7 years ago
    • 2.0.3                                ...           7 years ago
    • 2.0.2                                ...           7 years ago
    • 2.0.1                                ...           7 years ago
    • 2.0.0                                ...           7 years ago
    • 1.3.3                                ...           7 years ago
    • 1.3.2                                ...           7 years ago
    • 1.3.1                                ...           7 years ago
    • 1.3.0                                ...           7 years ago
    • 1.2.0                                ...           7 years ago
    • 1.1.2                                ...           8 years ago
    • 1.1.1                                ...           8 years ago
    • 1.1.0                                ...           8 years ago
    • 1.0.1                                ...           8 years ago
    • 1.0.0                                ...           8 years ago
    • 0.9.1                                ...           8 years ago
    • 0.9.0                                ...           8 years ago
    • 0.8.1                                ...           8 years ago
    • 0.8.0                                ...           8 years ago
    • 0.7.0                                ...           8 years ago
    • 0.6.5                                ...           8 years ago
    • 0.6.4                                ...           8 years ago
    • 0.6.3                                ...           9 years ago
    • 0.6.2                                ...           9 years ago
    • 0.6.1                                ...           9 years ago
    • 0.6.0                                ...           9 years ago
    • 0.5.0                                ...           10 years ago
    • 0.4.2                                ...           10 years ago
    • 0.4.1                                ...           10 years ago
    • 0.4.0                                ...           10 years ago
    • 0.3.3                                ...           10 years ago
    • 0.3.2                                ...           10 years ago
    • 0.3.1                                ...           10 years ago
    • 0.3.0                                ...           10 years ago
    • 0.2.5                                ...           10 years ago
    • 0.2.4                                ...           10 years ago
    • 0.2.3                                ...           10 years ago
    • 0.2.2                                ...           10 years ago
    • 0.2.1                                ...           10 years ago
    • 0.2.0                                ...           10 years ago
    • 0.1.4                                ...           10 years ago
    • 0.1.3                                ...           10 years ago
    • 0.1.2                                ...           10 years ago
    • 0.1.0                                ...           10 years ago
    • 0.0.9                                ...           10 years ago
    • 0.0.6                                ...           11 years ago
    • 0.0.5                                ...           11 years ago
    • 0.0.4                                ...           11 years ago
    • 0.0.3                                ...           11 years ago
    • 0.0.2                                ...           11 years ago
    • 0.0.1                                ...           11 years ago
    Maintainers (1)
    Downloads
    Total 3
    Today 0
    This Week 0
    This Month 0
    Last Day 0
    Last Week 0
    Last Month 3
    Dependencies (0)
    None
    Dev Dependencies (6)
    Dependents (1)

    © 2010 - cnpmjs.org x YWFE | Home | YWFE