npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongo-dql

v1.0.0

Published

A simple SQL-like data querying language to mongodb converter.

Downloads

23

Readme

Mongo DQL

A simple SQL-like data querying language to MongoDB converter.

The main aim of this module is to easily add support for filtering and sorting to MongoDB based web services. This is done through a simple querying language that is converted to MongoDB queries and sort definitions.

Installation

npm install --save mongo-dql

Usage

Basic usage

Sample basic usage with Mongoose and Express:

const MongoDQL = require('mongo-dql');
const mongoDQL = new MongoDQL();

exports.list = function(req, res, next) {
  const query = mongoDQL.parse(req.query.q);

  Model
    .find(query.where)
    .sort(query.orderBy)
    .then((models) => res.json(models));
}

Advanced usage

The complete signature of the MongoDQL constructor is the following:

MongoDQL(conditionTransform, sortMappings, defaults)

Condition transform

It's a function that can be used to transform conditions when they are created. The function must have the following signature:

function(identifier, operator, value)

For each parsed condition, the function receives the identifier, the mongo operator and the converted value as parameters. If it returns a falsy value, the condition will be added as usual, otherwise the returned value is used as the query for this condition.

This is useful in cases where a complex query should be simplified to clients, where a query should use internal model properties that are not exposed or where a query can not be expressed with the DQL.

The following example uses the transform function to simplify a complex condition:

function transform(identifier, operator, value) {
  if (identifier === 'name') {
    const pattern = new RegExp(_.escapeRegExp(value), 'i');

    return {$or: [
      {firstName: pattern},
      {lastName: pattern}
    ]}
  }
}

const mongoDQL = new MongoDQL(transform);

With this transform function, the condition name = 'value' would create a query that matches documents that contain value in either the firstName or lastName properties.

Sort mappings

It's an object whose properties are identifier names as they will appear in the query string and the values the corresponding properties to use in the final sort definition. This is mainly useful to use normalized fields for case insensitive sorting without exposing them.

Example:

const sortMappings = {name: 'normalized.name'};
const mongoDQL = new MongoDQL(null, sortMappings);

This would transform ORDER BY name into {'normalized.name': 1}.

Defaults

It's an object with the same structure as the result that defines default values to use for the where and orderBy properties. So if the parsed query does not have conditions, the where property of the defaults object will be used if defined, and the same goes for the sort definitions and the orderBy property.

Data Querying Language

The DQL used is SQL-like but simpler and more constrained. The general syntax is:

[conditions] [ORDER BY sort definitions]

The result of parsing a query string is an object with the following properties:

  • where: conditions converted to a MongoDB query
  • orderBy: sort definitions in MongoDB format

For example, the following query string:

namee = 'foulen' AND age > 10 ORDER BY age DESC, name ASC

would create the following object:

{
  where: {
    $and: [
      {name: 'foulen'},
      {age: {$gt: 10}}
    ]
  },
  orderBy: {
    age: -1,
    name: 1
  }
}

Value types

The values used in the conditions and sort definitions are converted to different types based on the following syntax:

  • String: '.*' (' can be escaped with \'), e.g. 'foulen\'s age is 18'
  • Number: [0-9]+ or [0-9]+.[0-9]+, e.g. 10, 10.1
  • Boolean: true or false
  • Null: null

Anything else is considered an error and makes the parser throw an exception.

Conditions

The supported conditions are:

  • identifier = value : {identifier: value}
  • identifier < value : {identifier: {$lt: value}}
  • identifier > value : {identifier: {$gt: value}}
  • identifier <= value : {identifier: {$le: value}}
  • identifier >= value : {identifier: {$ge: value}}
  • identifier LIKE value : {identifier: {$regexp: new RegExp(value)}}
  • identifier ILIKE value : {identifier: {$regexp: new RegExp(value, 'i')}}
  • identifier IN (v1, v2 ...) : {identifier: {$in: [v1, v2, ...]}}
  • identifier NOT IN (v1, v2 ...) : {identifier: {$nin: [v1, v2, ...]}}

As in SQL, conditions can be combined using AND and OR and grouped with parentheses.

Sort definitions

Sort definitions use the same syntax as in SQL, i.e. a comma separated list of identifier [dir] statements, where dir is either ASC or DESC and defaults to ASC if omitted.

Embedded documents

Identifiers can use dot-notation as supported by MongoDB to access properties of embedded documents, e.g. address.postcode = '123'.