Expressive query building for MongoDB



mquery is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, mquery runs on Node.js only with support for the MongoDB shell and browser environments planned for upcoming releases.

  • fluent query builder api
  • custom base query support
  • MongoDB 2.4 geoJSON support
  • method + option combinations validation
  • node.js driver compatibility
  • environment detection
  • debug support
  • separated collection implementations for maximum flexibility

require('mongodb').connect(uri, function (errdb) {
  if (err) return handleError(err);
  // get a collection 
  var collection = db.collection('artists');
  // pass it to the constructor 
  mquery(collection).find({..}, callback);
  // or pass it to the collection method 
  // or better yet, create a custom query constructor that has it always set 
  var Artist = mquery(collection).toConstructor();

mquery requires a collection object to work with. In the example above we just pass the collection object created using the official MongoDB driver.

Declares this query a find query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.

mquery().find(match, function (errdocs) {

Declares this query a findOne query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.

mquery().findOne(match, function (errdoc) {
  if (doc) {
    // the document may not be found 

Declares this query a count query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.

mquery().count(match, function (errnumber){
  console.log('we found %d matching documents', number);

Declares this query a remove query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.

mquery().remove(match, function (err){})

Declares this query an update query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run update(true).

mquery().update(match, updateDocument)
mquery().update(match, updateDocument, options)
// the following all execute the command 
mquery().update({$set: updateDocument, callback)
mquery().update(match, updateDocument, callback)
mquery().update(match, updateDocument, options, function (errresult){})
mquery().update(true) // executes (unsafe write) 

All paths passed that are not $atomic operations will become $set ops. For example:

mquery(collection).where({ _id: id }).update({ title: 'words' }, callback)


collection.update({ _id: id }, { $set: { title: 'words' }}, callback)

This behavior can be overridden using the overwrite option (see below).

Options are passed to the setOptions() method.

  • overwrite

Passing an empty object { } as the update document will result in a no-op unless the overwrite option is passed. Without the overwrite option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection.

var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true });
q.update({ }, callback); // overwrite with an empty doc 

The overwrite option isn't just for empty objects, it also provides a means to override the default $set conversion and send the update document as is.

// create a base query 
var base = mquery({ _id: 108 }).collection(collection).toConstructor();
base().findOne(function (errdoc) {
  console.log(doc); // { _id: 108, name: 'cajon' }) 
  base().setOptions({ overwrite: true }).update({ changed: true }, function (err) {
    base.findOne(function (errdoc) {
      console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten 
  • multi

Updates only modify a single document by default. To update multiple documents, set the multi option to true.

  .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback)
// another way of doing it 
mquery({ name: /^match/ })
  .setOptions({ multi: true })
  .update({ $addToSet: { arr: 4 }}, callback)
// update multiple documents with an empty doc 
var q = mquery(collection).where({ name: /^match/ });
q.setOptions({ multi: true, overwrite: true })
q.update({ });
q.update(function (errresult) {

Declares this query a findAndModify with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed.

When executed, the first matching document (if found) is modified according to the update document and passed back to the callback.

Options are passed to the setOptions() method.

  • new: boolean - true to return the modified document rather than the original. defaults to true
  • upsert: boolean - creates the object if it doesn't exist. defaults to false
  • sort: if multiple docs are found by the match condition, sets the sort order to choose which doc to update
query.findOneAndUpdate(match, updateDocument)
query.findOneAndUpdate(match, updateDocument, options)
// the following all execute the command 
query.findOneAndUpdate(updateDocument, callback)
query.findOneAndUpdate(match, updateDocument, callback)
query.findOneAndUpdate(match, updateDocument, options, function (errdoc) {
  if (doc) {
    // the document may not be found 

Declares this query a findAndModify with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed.

When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback.

Options are passed to the setOptions() method.

  • sort: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove
A.where().findOneAndRemove(match, options)
// the following all execute the command 
A.where().findOneAndRemove(match, callback)
A.where().findOneAndRemove(match, options, function (errdoc) {
  if (doc) {
    // the document may not be found 

Declares this query a distinct query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed.

mquery().distinct(match, field)
// the following all execute the command 
mquery().distinct(field, callback)
mquery().distinct(match, callback)
mquery().distinct(match, field, function (errresult) {

Executes the query.

mquery().findOne().where('route').intersects(polygon).exec(function (errdocs){})

Executes the query and returns a stream.

var stream = mquery().find().stream(options);
stream.on('data', cb);
stream.on('close', fn);

Note: this only works with find() operations.

Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the driver method.

Specifies an $all query condition

mquery().where('permission').all(['read', 'write'])

MongoDB documentation

Specifies arguments for an $and condition

mquery().and([{ color: 'green' }, { status: 'ok' }])

MongoDB documentation

Specifies a $box condition

var lowerLeft = [40.73083, -73.99756]
var upperRight= [40.741404,  -73.988135]
mquery().where('location').within().box(lowerLeft, upperRight)

MongoDB Documentation

Specifies a $center or $centerSphere condition.

var area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)'loc', area);
// for spherical calculations 
var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)'loc', area);

Specifies an $elemMatch condition

query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
query.elemMatch('comment', function (elem) {

MongoDB Documentation

Specifies the complementary comparison value for the path specified with where().

// is the same as 
mquery().where({ 'age': 49 });

Specifies an $exists condition

// { name: { $exists: true }} 
// { name: { $exists: false }} 
mquery().exists('name', false);

MongoDB Documentation

Specifies a $geometry condition

var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
// or 
var polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
// or 
var polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
// or 
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
// or 
query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] })

geometry() must come after intersects(), within(), or near().

The object argument must contain type and coordinates properties.

  • type String
  • coordinates Array

MongoDB Documentation

Specifies a $gt query condition.


MongoDB Documentation

Specifies a $gte query condition.

MongoDB Documentation


Specifies an $in query condition.

mquery().where('author_id').in([3, 48901, 761])

MongoDB Documentation

Declares an $geoIntersects query for geometry().

    type: 'LineString'
  , coordinates: [[180.0, 11.0], [180, 9.0]]
// geometry arguments are supported 
    type: 'LineString'
  , coordinates: [[180.0, 11.0], [180, 9.0]]

Must be used after where().

MongoDB Documentation

Specifies a $lt query condition.


MongoDB Documentation

Specifies a $lte query condition.


MongoDB Documentation

Specifies a $maxDistance query condition.

mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5)

MongoDB Documentation

Specifies a $mod condition

mquery().where('count').mod(2, 0)

MongoDB Documentation

Specifies a $ne query condition.


MongoDB Documentation

Specifies an $nin query condition.

mquery().where('author_id').nin([3, 48901, 761])

MongoDB Documentation

Specifies arguments for an $nor condition.

mquery().nor([{ color: 'green' }, { status: 'ok' }])

MongoDB Documentation

Specifies arguments for a $near or $nearSphere condition.

These operators return documents sorted by distance.

query.where('loc').near({ center: [10, 10] });
query.where('loc').near({ center: [10, 10], maxDistance: 5 });
query.near('loc', { center: [10, 10], maxDistance: 5 });
// GeoJSON 
query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }});
query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true });
query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] });
// For a $nearSphere condition, pass the `spherical` option. 
query.near({ center: [10, 10], maxDistance: 5, spherical: true });

MongoDB Documentation

Specifies arguments for an $or condition.

mquery().or([{ color: 'red' }, { status: 'emergency' }])

MongoDB Documentation

Specifies a $polygon condition

mquery().where('loc').within().polygon([10,20], [13, 25], [7,15])
mquery().polygon('loc', [10,20], [13, 25], [7,15])

MongoDB Documentation

Specifies a $regex query condition.


MongoDB Documentation

Specifies which document fields to include or exclude

// 1 means include, 0 means exclude 
mquery().select({ name: 1, address: 1, _id: 0 })
// or 
mquery().select('name address -_id')

When passing a string, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included.

// include a and b, exclude c'a b -c');
// or you may use object notation, useful when 
// you have keys already prefixed with a "-"{a: 1, b: 1, c: 0});

Cannot be used with distinct().

Determines if the query has selected any fields.

var query = mquery();
query.selected() // false'-name');
query.selected() // true 

Determines if the query has selected any fields inclusively.

var query = mquery().select('name');
query.selectedInclusively() // true 
var query = mquery();
query.selected() // false'-name');
query.selectedInclusively() // false 
query.selectedExclusively() // true 

Determines if the query has selected any fields exclusively.

var query = mquery().select('-name');
query.selectedExclusively() // true 
var query = mquery();
query.selected() // false'name');
query.selectedExclusively() // false 
query.selectedInclusively() // true 

Specifies a $size query condition.


MongoDB Documentation

Specifies a $slice projection for a path

mquery().where('comments').slice([-10, 5])

MongoDB Documentation

Sets a $geoWithin or $within argument for geo-spatial queries.

mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
mquery().where('loc').within({ polygon: [[],[],[],[]] });
mquery().where('loc').within([], [], []) // polygon 
mquery().where('loc').within([], []) // box 
mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry 

As of mquery 2.0, $geoWithin is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see mquery.use$geoWithin.

Must be used after where().

MongoDB Documentation

Specifies a path for use with chaining

// instead of writing: 
mquery().find({age: {$gte: 21, $lte: 65}});
// we can instead write: 
// passing query conditions is permitted too 
mquery().find().where({ name: 'vonderful' })
// chaining 
.where({ 'name': /^vonderful/i })

Specifies a $where condition.

Use $where when you need to select documents using a JavaScript expression.

query.$where('this.comments.length > 10 || > 5').exec(callback)
query.$where(function () {
  return this.comments.length > 10 || > 5;

Only use $where when you have a condition that cannot be met using other MongoDB operators like $lt. Be sure to read about all of its caveats before using.

Specifies the batchSize option.


Cannot be used with distinct().

MongoDB documentation

Specifies the comment option.

query.comment('login query');

Cannot be used with distinct().

MongoDB documentation

Sets query hints.

mquery().hint({ indexA: 1, indexB: -1 })

Cannot be used with distinct().

MongoDB documentation

Specifies the limit option.


Cannot be used with distinct().

MongoDB documentation

Specifies the maxScan option.


Cannot be used with distinct().

MongoDB documentation

Specifies the maxTimeMS option.


MongoDB documentation

Specifies the skip option.


Cannot be used with distinct().

MongoDB documentation

Sets the query sort order.

If an object is passed, key values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

// these are equivalent 
query.sort({ field: 'asc', test: -1 });
query.sort('field -test');

Cannot be used with distinct().

MongoDB documentation

Sets the readPreference option for the query.

mquery().read('p')  // same as primary 
mquery().read('pp') // same as primaryPreferred 
mquery().read('s')  // same as secondary 
mquery().read('sp') // same as secondaryPreferred 
mquery().read('n')  // same as nearest 
  • primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
  • secondary - Read from secondary if available, otherwise error.
  • primaryPreferred - Read from primary if available, otherwise a secondary.
  • secondaryPreferred - Read from a secondary if available, otherwise read from the primary.
  • nearest - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.


  • p primary
  • pp primaryPreferred
  • s secondary
  • sp secondaryPreferred
  • n nearest

To keep the separation of concerns between mquery and your driver clean, mquery#read() no longer handles specifying a second tags argument as of version 0.5. If you need to specify tags, pass any non-string argument as the first argument. mquery will pass this argument untouched to your collections methods later. For example:

// example of specifying tags using the Node.js driver 
var ReadPref = require('mongodb').ReadPreference;
var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]);

Read more about how to use read preferences here and here.

Sets the slaveOk option. true allows reading from secondaries.

deprecated use read() preferences instead if on mongodb >= 2.2

query.slaveOk() // true 

MongoDB documentation

Specifies this query as a snapshot query.

mquery().snapshot() // true 

Cannot be used with distinct().

MongoDB documentation

Sets tailable option.

mquery().tailable() <== true

Cannot be used with distinct().

MongoDB Documentation

Sets the querys collection.


Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error.

mquery().find(..).then(success, error);

This is very useful when combined with co or koa, which automatically resolve promise-like objects for you.

  var doc = yield mquery().findOne({ _id: 499 });
  console.log(doc); // { _id: 499, name: 'amazing', .. } 

NOTE: The returned promise is a bluebird promise but this is customizable. If you want to use your favorite promise library, simply set mquery.Promise = YourPromiseConstructor. Your Promise must be promises A+ compliant.

Returns a thunk which when called runs the query's exec method passing the results to the callback.

var thunk = mquery(collection).find({..}).thunk();
thunk(function(errresults) {

Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged.

var drum = mquery({ type: 'drum' }).collection(instruments);
var redDrum = mqery({ color: 'red' }).merge(drum);
redDrum.count(function (errn) {
  console.log('there are %d red drums', n);

Internally uses mquery.canMerge to determine validity.

Sets query options.

mquery().setOptions({ collection: coll, limit: 20 })

* denotes a query helper method is also available

Set a function to trace this query. Useful for profiling or logging.

function traceFunction (methodqueryInfoquery) {
  console.log('starting ' + method + ' query');
  return function (errresultmillis) {
    console.log('finished ' + method + ' query in ' + millis + 'ms');
mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb);

The trace function is passed (method, queryInfo, query)

  • method is the name of the method being called (e.g. findOne)
  • queryInfo contains information about the query:
  • conditions: query conditions/criteria
  • options: options such as sort, fields, etc
  • doc: document being updated
  • query is the query object

The trace function should return a callback function which accepts:

  • err: error, if any
  • result: result, if any
  • millis: time spent waiting for query result

NOTE: stream requests are not traced.

Similar to setTraceFunction() but automatically applied to all queries.


Determines if conditions can be merged using mquery().merge().

var query = mquery({ type: 'drum' });
var okToMerge = mquery.canMerge(anObject)
if (okToMerge) {

MongoDB 2.4 introduced the $geoWithin operator which replaces and is 100% backward compatible with $within. As of mquery 0.2, we default to using $geoWithin for all within() calls.

If you are running MongoDB < 2.4 this will be problematic. To force mquery to be backward compatible and always use $within, set the mquery.use$geoWithin flag to false.

mquery.use$geoWithin = false;

Often times we want custom base queries that encapsulate predefined criteria. With mquery this is easy. First create the query you want to reuse and call its toConstructor() method which returns a new subclass of mquery that retains all options and criteria of the original.

var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor();
// use it! 
greatMovies().count(function (errn) {
  console.log('There are %d great movies', n);
greatMovies().where({ name: /^Life/ }).select('name').find(function (errdocs) {

Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a distinct query does not support specifying options like hint or field selection. In this case an error will be thrown so you can catch these mistakes in development.

Debug mode is provided through the use of the debug module. To enable:

DEBUG=mquery node yourprogram.js

Read the debug module documentation for more details.

mquery clones query arguments before passing them to a collection method for execution. This prevents accidental side-affects to the objects you pass. To clone ObjectIds we need to make some assumptions.

First, to check if an object is an ObjectId, we check its constructors name. If it matches either ObjectId or ObjectID we clone it.

To clone ObjectIds, we call its optional clone method. If a clone method does not exist, we fall back to calling new obj.constructor( We assume, for compatibility with the Node.js driver, that the ObjectId instance has a public id property and that when creating an ObjectId instance we can pass that id as an argument.

mquery supports specifying Read Preferences to control from which MongoDB node your query will read. The Read Preferences spec also support specifying tags. To pass tags, some drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. mquery will store whatever you provide and pass later to your collection during execution.

  • mongo shell compatibility
  • browser compatibility
$ npm install mquery