{"id":13459069,"url":"https://github.com/mongoosejs/mquery","last_synced_at":"2026-01-15T22:20:33.075Z","repository":{"id":5952270,"uuid":"7173240","full_name":"mongoosejs/mquery","owner":"mongoosejs","description":"Expressive MongoDB query builder","archived":false,"fork":false,"pushed_at":"2025-11-18T15:46:50.000Z","size":747,"stargazers_count":480,"open_issues_count":10,"forks_count":70,"subscribers_count":15,"default_branch":"master","last_synced_at":"2026-01-13T04:06:26.217Z","etag":null,"topics":["javascript","mongodb","nodejs","query-builder"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mongoosejs.png","metadata":{"files":{"readme":"README.md","changelog":"History.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2012-12-14T22:55:16.000Z","updated_at":"2025-12-08T14:03:27.000Z","dependencies_parsed_at":"2026-01-13T04:06:42.397Z","dependency_job_id":null,"html_url":"https://github.com/mongoosejs/mquery","commit_stats":{"total_commits":376,"total_committers":37,"mean_commits":"10.162162162162161","dds":0.7074468085106382,"last_synced_commit":"e7a8a3099ef282a2d9af36a2880981871adfe9fd"},"previous_names":["aheckmann/mquery"],"tags_count":75,"template":false,"template_full_name":null,"purl":"pkg:github/mongoosejs/mquery","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoosejs%2Fmquery","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoosejs%2Fmquery/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoosejs%2Fmquery/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoosejs%2Fmquery/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mongoosejs","download_url":"https://codeload.github.com/mongoosejs/mquery/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongoosejs%2Fmquery/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28472626,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-15T22:13:38.078Z","status":"ssl_error","status_checked_at":"2026-01-15T22:12:11.737Z","response_time":62,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","mongodb","nodejs","query-builder"],"created_at":"2024-07-31T09:01:02.664Z","updated_at":"2026-01-15T22:20:33.069Z","avatar_url":"https://github.com/mongoosejs.png","language":"JavaScript","readme":"# mquery\n\n`mquery` is a fluent mongodb query builder designed to run in multiple environments.\n\n[![Build Status](https://travis-ci.org/aheckmann/mquery.svg?branch=master)](https://travis-ci.org/aheckmann/mquery)\n[![NPM version](https://badge.fury.io/js/mquery.svg)](http://badge.fury.io/js/mquery)\n\n[![npm](https://nodei.co/npm/mquery.png)](https://www.npmjs.com/package/mquery)\n\n## Features\n\n- fluent query builder api\n- custom base query support\n- MongoDB 2.4 geoJSON support\n- method + option combinations validation\n- node.js driver compatibility\n- environment detection\n- [debug](https://github.com/visionmedia/debug) support\n- separated collection implementations for maximum flexibility\n\n## Use\n\n```js\nconst mongo = require('mongodb');\n\nconst client = new mongo.MongoClient(uri);\nawait client.connect();\n// get a collection\nconst collection = client.collection('artists');\n\n// pass it to the constructor\nawait mquery(collection).find({...});\n\n// or pass it to the collection method\nconst docs = await mquery().find({...}).collection(collection);\n\n// or better yet, create a custom query constructor that has it always set\nconst Artist = mquery(collection).toConstructor();\nconst docs = await Artist().find(...).where(...);\n```\n\n`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native).\n\n## Fluent API\n\n- [mquery](#mquery)\n  - [Features](#features)\n  - [Use](#use)\n  - [Fluent API](#fluent-api)\n  - [Helpers](#helpers)\n    - [find()](#find)\n    - [findOne()](#findone)\n    - [countDocuments()](#countdocuments)\n    - [estimatedDocumentCount()](#estimateddocumentcount)\n    - [findOneAndUpdate()](#findoneandupdate)\n        - [findOneAndUpdate() options](#findoneandupdate-options)\n    - [findOneAndReplace()](#findoneandreplace)\n        - [findOneAndReplace() options](#findoneandreplace-options)\n    - [findOneAndRemove()](#findoneandremove)\n        - [findOneAndRemove() options](#findoneandremove-options)\n    - [distinct()](#distinct)\n    - [updateMany()](#updatemany)\n    - [updateOne()](#updateone)\n    - [replaceOne()](#replaceone)\n    - [deleteOne()](#deleteone)\n    - [deleteMany()](#deletemany)\n    - [exec()](#exec)\n    - [cursor()](#cursor)\n    - [stream()](#stream)\n    - [all()](#all)\n    - [and()](#and)\n    - [box()](#box)\n    - [circle()](#circle)\n    - [elemMatch()](#elemmatch)\n    - [equals()](#equals)\n    - [eq()](#eq)\n    - [exists()](#exists)\n    - [geometry()](#geometry)\n    - [gt()](#gt)\n    - [gte()](#gte)\n    - [in()](#in)\n    - [intersects()](#intersects)\n    - [lt()](#lt)\n    - [lte()](#lte)\n    - [maxDistance()](#maxdistance)\n    - [mod()](#mod)\n    - [ne()](#ne)\n    - [nin()](#nin)\n    - [nor()](#nor)\n    - [near()](#near)\n      - [Example](#example)\n    - [or()](#or)\n    - [polygon()](#polygon)\n    - [regex()](#regex)\n    - [select()](#select)\n        - [String syntax](#string-syntax)\n    - [selected()](#selected)\n    - [selectedInclusively()](#selectedinclusively)\n    - [selectedExclusively()](#selectedexclusively)\n    - [size()](#size)\n    - [slice()](#slice)\n    - [within()](#within)\n    - [where()](#where)\n    - [$where()](#where-1)\n    - [batchSize()](#batchsize)\n    - [collation()](#collation)\n    - [comment()](#comment)\n    - [hint()](#hint)\n    - [j()](#j)\n    - [limit()](#limit)\n    - [maxTime()](#maxtime)\n    - [skip()](#skip)\n    - [sort()](#sort)\n    - [read()](#read)\n        - [Preferences:](#preferences)\n        - [Preference Tags:](#preference-tags)\n    - [readConcern()](#readconcern)\n        - [Read Concern Level:](#read-concern-level)\n    - [writeConcern()](#writeconcern)\n        - [Write Concern:](#write-concern)\n    - [slaveOk()](#slaveok)\n    - [tailable()](#tailable)\n    - [wtimeout()](#wtimeout)\n  - [Helpers](#helpers-1)\n    - [collection()](#collection)\n    - [then()](#then)\n    - [merge(object)](#mergeobject)\n    - [setOptions(options)](#setoptionsoptions)\n        - [setOptions() options](#setoptions-options)\n    - [setTraceFunction(func)](#settracefunctionfunc)\n    - [mquery.setGlobalTraceFunction(func)](#mquerysetglobaltracefunctionfunc)\n    - [mquery.canMerge(conditions)](#mquerycanmergeconditions)\n  - [mquery.use$geoWithin](#mqueryusegeowithin)\n  - [Custom Base Queries](#custom-base-queries)\n  - [Validation](#validation)\n  - [Debug support](#debug-support)\n  - [General compatibility](#general-compatibility)\n      - [ObjectIds](#objectids)\n      - [Read Preferences](#read-preferences)\n  - [Future goals](#future-goals)\n  - [Installation](#installation)\n  - [License](#license)\n\n## Helpers\n\n- [collection](#collection)\n- [then](#then)\n- [merge](#mergeobject)\n- [setOptions](#setoptionsoptions)\n- [setTraceFunction](#settracefunctionfunc)\n- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc)\n- [mquery.canMerge](#mquerycanmergeconditions)\n- [mquery.use$geoWithin](#mqueryusegeowithin)\n\n### find()\n\nDeclares this query a _find_ query. Optionally pass a match clause.\n\n```js\nmquery().find()\nmquery().find(match)\nawait mquery().find()\nconst docs = await mquery().find(match);\nassert(Array.isArray(docs));\n```\n\n### findOne()\n\nDeclares this query a _findOne_ query. Optionally pass a match clause.\n\n```js\nmquery().findOne()\nmquery().findOne(match)\nawait mquery().findOne()\nconst doc = await mquery().findOne(match);\nif (doc) {\n  // the document may not be found\n  console.log(doc);\n}\n```\n\n### countDocuments()\n\nDeclares this query a _countDocuments_ query. Optionally pass a match clause.\n\n```js\nmquery().countDocuments()\nmquery().countDocuments(match)\nawait mquery().countDocuments()\nconst number = await mquery().countDocuments(match);\nconsole.log('we found %d matching documents', number);\n```\n\n### estimatedDocumentCount()\n\nDeclares this query an _estimatedDocumentCount_ query. Gets an estimated count of documents in a collection using collection metadata.\n\n```js\nmquery().estimatedDocumentCount()\nconst number = await mquery().estimatedDocumentCount();\nconsole.log('estimated documents: %d', number);\n```\n\n### findOneAndUpdate()\n\nDeclares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options.\n\nWhen executed, the first matching document (if found) is modified according to the update document and passed back.\n\n#### findOneAndUpdate() options\n\nOptions are passed to the `setOptions()` method.\n\n- `new`: boolean - true to return the modified document rather than the original. defaults to false\n- `upsert`: boolean - creates the object if it doesn't exist. defaults to false\n- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update\n\n```js\nquery.findOneAndUpdate()\nquery.findOneAndUpdate(updateDocument)\nquery.findOneAndUpdate(match, updateDocument)\nquery.findOneAndUpdate(match, updateDocument, options)\n\n// the following all execute the command\nawait query.findOneAndUpdate()\nawait query.findOneAndUpdate(updateDocument)\nawait query.findOneAndUpdate(match, updateDocument)\nconst doc = await query.findOneAndUpdate(match, updateDocument, options);\nif (doc) {\n  // the document may not be found\n  console.log(doc);\n}\n```\n\n### findOneAndReplace()\n\nDeclares this query a _findOneAndReplace_ query. Finds a matching document, replaces it with the provided replacement, and returns the found document (if any).\n\n#### findOneAndReplace() options\n\nOptions are passed to the `setOptions()` method.\n\n- `new`: boolean - true to return the modified document rather than the original. defaults to false\n- `upsert`: boolean - creates the object if it doesn't exist. defaults to false\n- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to replace\n\n```js\nquery.findOneAndReplace()\nquery.findOneAndReplace(replacement)\nquery.findOneAndReplace(match, replacement)\nquery.findOneAndReplace(match, replacement, options)\n\n// the following all execute the command\nawait query.findOneAndReplace()\nawait query.findOneAndReplace(replacement)\nawait query.findOneAndReplace(match, replacement)\nconst doc = await query.findOneAndReplace(match, replacement, options);\nif (doc) {\n  // the document may not be found\n  console.log(doc);\n}\n```\n\n### findOneAndRemove()\n\nDeclares this query a _findAndModify_ with remove query. Alias of findOneAndDelete.\nOptionally pass a match clause, options.\n\nWhen executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed as a result.\n\n#### findOneAndRemove() options\n\nOptions are passed to the `setOptions()` method.\n\n- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove\n\n```js\nA.where().findOneAndDelete()\nA.where().findOneAndRemove()\nA.where().findOneAndRemove(match)\nA.where().findOneAndRemove(match, options)\n\n// the following all execute the command\nawait A.where().findOneAndRemove()\nawait A.where().findOneAndRemove(match)\nconst doc = await A.where().findOneAndRemove(match, options);\nif (doc) {\n  // the document may not be found\n  console.log(doc);\n}\n```\n\n### distinct()\n\nDeclares this query a _distinct_ query. Optionally pass the distinct field, a match clause.\n\n```js\nmquery().distinct()\nmquery().distinct(match)\nmquery().distinct(match, field)\nmquery().distinct(field)\n\n// the following all execute the command\nawait mquery().distinct()\nawait mquery().distinct(field)\nawait mquery().distinct(match)\nconst result = await mquery().distinct(match, field);\nconsole.log(result);\n```\n\n### updateMany()\n\nDeclares this query an _updateMany_ query. Updates all documents that match `criteria`.\n\nWhen executed, the first argument is the query, and the second argument is the update document.\n\n_All paths passed that are not $atomic operations will become $set ops._\n\n```js\nmquery().updateMany({ name: /^match/ }, { field: 'value' })\nawait mquery().updateMany({ name: /^match/ }, { field: 'value' })\nawait mquery().where({ name: /^match/ }).updateMany({ field: 'value' })\n```\n\n### updateOne()\n\nDeclares this query an _updateOne_ query. Updates only the first document that matches `criteria`.\n\nWhen executed, the first argument is the query, and the second argument is the update document.\n\n_All paths passed that are not $atomic operations will become $set ops._\n\n```js\nmquery().updateOne({ name: 'match' }, { field: 'value' })\nawait mquery().updateOne({ name: 'match' }, { field: 'value' })\nawait mquery().where({ name: 'match' }).updateOne({ field: 'value' })\n```\n\n### replaceOne()\n\nDeclares this query a _replaceOne_ query. Replaces the first document that matches `criteria` with the provided replacement document.\n\nSimilar to `updateOne()`, except `replaceOne()` is not allowed to use atomic modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always replace the existing doc.\n\n```js\nmquery().replaceOne({ _id: 1 }, { name: 'new name', age: 25 })\nawait mquery().replaceOne({ _id: 1 }, { name: 'new name', age: 25 })\n```\n\n### deleteOne()\n\nDeclares this query a _deleteOne_ query. Deletes the first document that matches `criteria`.\n\n```js\nmquery().deleteOne({ name: 'match' })\nawait mquery().deleteOne({ name: 'match' })\nawait mquery().where({ name: 'match' }).deleteOne()\n```\n\n### deleteMany()\n\nDeclares this query a _deleteMany_ query. Deletes all documents that match `criteria`.\n\n```js\nmquery().deleteMany({ name: /^match/ })\nawait mquery().deleteMany({ name: /^match/ })\nawait mquery().where({ name: /^match/ }).deleteMany()\n```\n\n### exec()\n\nExecutes the query.\n\n```js\nconst docs = await mquery().findOne().where('route').intersects(polygon).exec()\n```\n\n### cursor()\n\nReturns a cursor for the given `find` query.\n\n```js\nconst cursor = mquery().find({ name: /^match/ }).cursor();\ncursor.on('data', function(doc) {\n  console.log(doc);\n});\ncursor.on('end', function() {\n  console.log('done');\n});\n```\n\nNote: this only works with `find()` operations.\n\n### stream()\n\nExecutes the query and returns a stream.\n\n```js\nvar stream = mquery().find().stream(options);\nstream.on('data', cb);\nstream.on('close', fn);\n```\n\nNote: this only works with `find()` operations.\n\nNote: 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](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream).\n\n---\n\n### all()\n\nSpecifies an `$all` query condition\n\n```js\nmquery().where('permission').all(['read', 'write'])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/)\n\n### and()\n\nSpecifies arguments for an `$and` condition\n\n```js\nmquery().and([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/)\n\n### box()\n\nSpecifies a `$box` condition\n\n```js\nvar lowerLeft = [40.73083, -73.99756]\nvar upperRight= [40.741404,  -73.988135]\n\nmquery().where('location').within().box(lowerLeft, upperRight)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/)\n\n### circle()\n\nSpecifies a `$center` or `$centerSphere` condition.\n\n```js\nvar area = { center: [50, 50], radius: 10, unique: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n\n// for spherical calculations\nvar area = { center: [50, 50], radius: 10, unique: true, spherical: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n```\n\n- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/)\n- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/)\n\n### elemMatch()\n\nSpecifies an `$elemMatch` condition\n\n```js\nquery.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n\nquery.elemMatch('comment', function (elem) {\n  elem.where('author').equals('autobot');\n  elem.where('votes').gte(5);\n})\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/)\n\n### equals()\n\nSpecifies the complementary comparison value for the path specified with `where()`.\n\n```js\nmquery().where('age').equals(49);\n\n// is the same as\n\nmquery().where({ 'age': 49 });\n```\n\n### eq()\n\nAlias of `equals()`. Specifies the complementary comparison value for the path specified with `where()`.\n\n```js\nmquery().where('age').eq(49);\n\n// is the same as\n\nmquery().where('age').equals(49);\n\n// is the same as\n\nmquery().where({ 'age': 49 });\n```\n\n### exists()\n\nSpecifies an `$exists` condition\n\n```js\n// { name: { $exists: true }}\nmquery().where('name').exists()\nmquery().where('name').exists(true)\nmquery().exists('name')\n\n// { name: { $exists: false }}\nmquery().where('name').exists(false);\nmquery().exists('name', false);\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/)\n\n### geometry()\n\nSpecifies a `$geometry` condition\n\n```js\nvar polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]\nquery.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })\n\n// or\nvar polyB = [[ 0, 0 ], [ 1, 1 ]]\nquery.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })\n\n// or\nvar polyC = [ 0, 0 ]\nquery.where('loc').within().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] })\n```\n\n`geometry()` **must** come after `intersects()`, `within()`, or `near()`.\n\nThe `object` argument must contain `type` and `coordinates` properties.\n\n- type `String`\n- coordinates `Array`\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/)\n\n### gt()\n\nSpecifies a `$gt` query condition.\n\n```js\nmquery().where('clicks').gt(999)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/)\n\n### gte()\n\nSpecifies a `$gte` query condition.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/)\n\n```js\nmquery().where('clicks').gte(1000)\n```\n\n### in()\n\nSpecifies an `$in` query condition.\n\n```js\nmquery().where('author_id').in([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/)\n\n### intersects()\n\nDeclares an `$geoIntersects` query for `geometry()`.\n\n```js\nquery.where('path').intersects().geometry({\n    type: 'LineString'\n  , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n\n// geometry arguments are supported\nquery.where('path').intersects({\n    type: 'LineString'\n  , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n```\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/)\n\n### lt()\n\nSpecifies a `$lt` query condition.\n\n```js\nmquery().where('clicks').lt(50)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/)\n\n### lte()\n\nSpecifies a `$lte` query condition.\n\n```js\nmquery().where('clicks').lte(49)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/)\n\n### maxDistance()\n\nSpecifies a `$maxDistance` query condition.\n\n```js\nmquery().where('location').near({ center: [139, 74.3] }).maxDistance(5)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/)\n\n### mod()\n\nSpecifies a `$mod` condition\n\n```js\nmquery().where('count').mod(2, 0)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/)\n\n### ne()\n\nSpecifies a `$ne` query condition.\n\n```js\nmquery().where('status').ne('ok')\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/)\n\n### nin()\n\nSpecifies an `$nin` query condition.\n\n```js\nmquery().where('author_id').nin([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/)\n\n### nor()\n\nSpecifies arguments for an `$nor` condition.\n\n```js\nmquery().nor([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/)\n\n### near()\n\nSpecifies arguments for a `$near` or `$nearSphere` condition.\n\nThese operators return documents sorted by distance.\n\n#### Example\n\n```js\nquery.where('loc').near({ center: [10, 10] });\nquery.where('loc').near({ center: [10, 10], maxDistance: 5 });\nquery.near('loc', { center: [10, 10], maxDistance: 5 });\n\n// GeoJSON\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }});\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true });\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] });\n\n// For a $nearSphere condition, pass the `spherical` option.\nquery.near({ center: [10, 10], maxDistance: 5, spherical: true });\n```\n\n[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing)\n\n### or()\n\nSpecifies arguments for an `$or` condition.\n\n```js\nmquery().or([{ color: 'red' }, { status: 'emergency' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/)\n\n### polygon()\n\nSpecifies a `$polygon` condition\n\n```js\nmquery().where('loc').within().polygon([10,20], [13, 25], [7,15])\nmquery().polygon('loc', [10,20], [13, 25], [7,15])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/)\n\n### regex()\n\nSpecifies a `$regex` query condition.\n\n```js\nmquery().where('name').regex(/^sixstepsrecords/)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/)\n\n### select()\n\nSpecifies which document fields to include or exclude\n\n```js\n// 1 means include, 0 means exclude\nmquery().select({ name: 1, address: 1, _id: 0 })\n\n// or\n\nmquery().select('name address -_id')\n```\n\n#### String syntax\n\nWhen passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included.\n\n```js\n// include a and b, exclude c\nquery.select('a b -c');\n\n// or you may use object notation, useful when\n// you have keys already prefixed with a \"-\"\nquery.select({a: 1, b: 1, c: 0});\n```\n\n_Cannot be used with `distinct()`._\n\n### selected()\n\nDetermines if the query has selected any fields.\n\n```js\nvar query = mquery();\nquery.selected() // false\nquery.select('-name');\nquery.selected() // true\n```\n\n### selectedInclusively()\n\nDetermines if the query has selected any fields inclusively.\n\n```js\nvar query = mquery().select('name');\nquery.selectedInclusively() // true\n\nvar query = mquery();\nquery.selected() // false\nquery.select('-name');\nquery.selectedInclusively() // false\nquery.selectedExclusively() // true\n```\n\n### selectedExclusively()\n\nDetermines if the query has selected any fields exclusively.\n\n```js\nvar query = mquery().select('-name');\nquery.selectedExclusively() // true\n\nvar query = mquery();\nquery.selected() // false\nquery.select('name');\nquery.selectedExclusively() // false\nquery.selectedInclusively() // true\n```\n\n### size()\n\nSpecifies a `$size` query condition.\n\n```js\nmquery().where('someArray').size(6)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/)\n\n### slice()\n\nSpecifies a `$slice` projection for a `path`\n\n```js\nmquery().where('comments').slice(5)\nmquery().where('comments').slice(-5)\nmquery().where('comments').slice([-10, 5])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/)\n\n### within()\n\nSets a `$geoWithin` or `$within` argument for geo-spatial queries.\n\n```js\nmquery().within().box()\nmquery().within().circle()\nmquery().within().geometry()\n\nmquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });\nmquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });\nmquery().where('loc').within({ polygon: [[],[],[],[]] });\n\nmquery().where('loc').within([], [], []) // polygon\nmquery().where('loc').within([], []) // box\nmquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry\n```\n\nAs of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB \u003c 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin).\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/)\n\n### where()\n\nSpecifies a `path` for use with chaining\n\n```js\n// instead of writing:\nmquery().find({age: {$gte: 21, $lte: 65}});\n\n// we can instead write:\nmquery().where('age').gte(21).lte(65);\n\n// passing query conditions is permitted too\nmquery().find().where({ name: 'vonderful' })\n\n// chaining\nawait mquery()\n  .where('age').gte(21).lte(65)\n  .where({ 'name': /^vonderful/i })\n  .where('friends').slice(10)\n  .exec()\n```\n\n### $where()\n\nSpecifies a `$where` condition.\n\nUse `$where` when you need to select documents using a JavaScript expression.\n\n```js\nawait query.$where('this.comments.length \u003e 10 || this.name.length \u003e 5').exec()\n\nquery.$where(function () {\n  return this.comments.length \u003e 10 || this.name.length \u003e 5;\n})\n```\n\nOnly 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](http://docs.mongodb.org/manual/reference/operator/where/) before using.\n\n---\n\n### batchSize()\n\nSpecifies the batchSize option.\n\n```js\nquery.batchSize(100)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/)\n\n### collation()\n\nSpecifies the collation option.\n\n```js\nquery.collation({ locale: \"en_US\", strength: 1 })\n```\n\n[MongoDB documentation](https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation)\n\n### comment()\n\nSpecifies the comment option.\n\n```js\nquery.comment('login query');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/)\n\n### hint()\n\nSets query hints.\n\n```js\nmquery().hint({ indexA: 1, indexB: -1 })\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/)\n\n### j()\n\nRequests acknowledgement that this operation has been persisted to MongoDB's on-disk journal.\n\nThis option is only valid for operations that write to the database:\n\n- `deleteOne()`\n- `deleteMany()`\n- `findOneAndDelete()`\n- `findOneAndUpdate()`\n- `updateOne()`\n- `updateMany()`\n\nDefaults to the `j` value if it is specified in [writeConcern](#writeconcern)\n\n```js\nmquery().j(true);\n```\n\n### limit()\n\nSpecifies the limit option.\n\n```js\nquery.limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/)\n\n### maxTime()\n\nSpecifies the maxTimeMS option.\n\n```js\nquery.maxTime(100)\nquery.maxTimeMS(100)\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/)\n\n### skip()\n\nSpecifies the skip option.\n\n```js\nquery.skip(100).limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/)\n\n### sort()\n\nSets the query sort order.\n\nIf an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.\n\nIf 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.\n\n```js\n// these are equivalent\nquery.sort({ field: 'asc', test: -1 });\nquery.sort('field -test');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/)\n\n### read()\n\nSets the readPreference option for the query.\n\n```js\nmquery().read('primary')\nmquery().read('p')  // same as primary\n\nmquery().read('primaryPreferred')\nmquery().read('pp') // same as primaryPreferred\n\nmquery().read('secondary')\nmquery().read('s')  // same as secondary\n\nmquery().read('secondaryPreferred')\nmquery().read('sp') // same as secondaryPreferred\n\nmquery().read('nearest')\nmquery().read('n')  // same as nearest\n\nmquery().setReadPreference('primary') // alias of .read()\n```\n\n#### Preferences:\n\n- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.\n- `secondary` - Read from secondary if available, otherwise error.\n- `primaryPreferred` - Read from primary if available, otherwise a secondary.\n- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary.\n- `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.\n\nAliases\n\n- `p`   primary\n- `pp`  primaryPreferred\n- `s`   secondary\n- `sp`  secondaryPreferred\n- `n`   nearest\n\n#### Preference Tags:\n\nTo keep the separation of concerns between `mquery` and your driver\nclean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5.\nIf you need to specify tags, pass any non-string argument as the first argument.\n`mquery` will pass this argument untouched to your collections methods later.\nFor example:\n\n```js\n// example of specifying tags using the Node.js driver\nvar ReadPref = require('mongodb').ReadPreference;\nvar preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]);\nmquery(...).read(preference).exec();\n```\n\nRead more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).\n\n### readConcern()\n\nSets the readConcern option for the query.\n\n```js\n// local\nmquery().readConcern('local')\nmquery().readConcern('l')\nmquery().r('l')\n\n// available\nmquery().readConcern('available')\nmquery().readConcern('a')\nmquery().r('a')\n\n// majority\nmquery().readConcern('majority')\nmquery().readConcern('m')\nmquery().r('m')\n\n// linearizable\nmquery().readConcern('linearizable')\nmquery().readConcern('lz')\nmquery().r('lz')\n\n// snapshot\nmquery().readConcern('snapshot')\nmquery().readConcern('s')\nmquery().r('s')\n```\n\n#### Read Concern Level:\n\n- `local` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.2+)\n- `available` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.6+)\n- `majority` - The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. (MongoDB 3.2+)\n- `linearizable` - The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. (MongoDB 3.4+)\n- `snapshot` - Only available for operations within multi-document transactions. Upon transaction commit with write concern \"majority\", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. (MongoDB 4.0+)\n\nAliases\n\n- `l`   local\n- `a`   available\n- `m`   majority\n- `lz`  linearizable\n- `s`   snapshot\n\nRead more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).\n\n### writeConcern()\n\nSets the writeConcern option for the query.\n\nThis option is only valid for operations that write to the database:\n\n- `deleteOne()`\n- `deleteMany()`\n- `findOneAndDelete()`\n- `findOneAndUpdate()`\n- `updateOne()`\n- `updateMany()`\n\n```js\nmquery().writeConcern(0)\nmquery().writeConcern(1)\nmquery().writeConcern({ w: 1, j: true, wtimeout: 2000 })\nmquery().writeConcern('majority')\nmquery().writeConcern('m') // same as majority\nmquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead\nmquery().w(1) // w is alias of writeConcern\n```\n\n#### Write Concern:\n\nwriteConcern({ w: `\u003cvalue\u003e`, j: `\u003cboolean\u003e`, wtimeout: `\u003cnumber\u003e` }`)\n\n- the w option to request acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags\n- the j option to request acknowledgement that the write operation has been written to the journal\n- the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely\n\nCan be break down to use the following syntax:\n\nmquery().w(`\u003cvalue\u003e`).j(`\u003cboolean\u003e`).wtimeout(`\u003cnumber\u003e`)\n\nRead more about how to use write concern [here](https://docs.mongodb.com/manual/reference/write-concern/)\n\n### slaveOk()\n\nSets the slaveOk option. `true` allows reading from secondaries.\n\n**deprecated** use [read()](#read) preferences instead if on mongodb \u003e= 2.2\n\n```js\nquery.slaveOk() // true\nquery.slaveOk(true)\nquery.slaveOk(false)\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/)\n\n### tailable()\n\nSets tailable option.\n\n```js\nmquery().tailable() \u003c== true\nmquery().tailable(true)\nmquery().tailable(false)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/)\n\n### wtimeout()\n\nSpecifies a time limit, in milliseconds, for the write concern. If `w \u003e 1`, it is maximum amount of time to\nwait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout.\n\nThis option is only valid for operations that write to the database:\n\n- `deleteOne()`\n- `deleteMany()`\n- `findOneAndDelete()`\n- `findOneAndUpdate()`\n- `updateOne()`\n- `updateMany()`\n\nDefaults to `wtimeout` value if it is specified in [writeConcern](#writeconcern)\n\n```js\nmquery().wtimeout(2000)\nmquery().wTimeout(2000)\n```\n\n## Helpers\n\n### collection()\n\nSets the querys collection.\n\n```js\nmquery().collection(aCollection)\n```\n\n### then()\n\nExecutes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error.\n\n```js\nmquery().find(..).then(success, error);\n```\n\nThis is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you.\n\n```js\nco(function*(){\n  var doc = yield mquery().findOne({ _id: 499 });\n  console.log(doc); // { _id: 499, name: 'amazing', .. }\n})();\n```\n\n_NOTE_:\nThe returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to\nuse your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`.\nYour `Promise` must be [promises A+](http://promisesaplus.com/) compliant.\n\n### merge(object)\n\nMerges other mquery or match condition objects into this one. When an mquery instance is passed, its match conditions, field selection and options are merged.\n\n```js\nconst drum = mquery({ type: 'drum' }).collection(instruments);\nconst redDrum = mquery({ color: 'red' }).merge(drum);\nconst n = await redDrum.count();\nconsole.log('there are %d red drums', n);\n```\n\nInternally uses `mquery.canMerge` to determine validity.\n\n### setOptions(options)\n\nSets query options.\n\n```js\nmquery().setOptions({ collection: coll, limit: 20 })\n```\n\n#### setOptions() options\n\n- [tailable](#tailable) *\n- [sort](#sort) *\n- [limit](#limit) *\n- [skip](#skip) *\n- [maxTime](#maxtime) *\n- [batchSize](#batchsize) *\n- [comment](#comment) *\n- [hint](#hint) *\n- [collection](#collection): the collection to query against\n\n_* denotes a query helper method is also available_\n\n### setTraceFunction(func)\n\nSet a function to trace this query. Useful for profiling or logging.\n\n```js\nfunction traceFunction (method, queryInfo, query) {\n  console.log('starting ' + method + ' query');\n\n  return function (err, result, millis) {\n    console.log('finished ' + method + ' query in ' + millis + 'ms');\n  };\n}\n\nmquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb);\n```\n\nThe trace function is passed (method, queryInfo, query)\n\n- method is the name of the method being called (e.g. findOne)\n- queryInfo contains information about the query:\n  - conditions: query conditions/criteria\n  - options: options such as sort, fields, etc\n  - doc: document being updated\n- query is the query object\n\nThe trace function should return a callback function which accepts:\n- err: error, if any\n- result: result, if any\n- millis: time spent waiting for query result\n\nNOTE: stream requests are not traced.\n\n### mquery.setGlobalTraceFunction(func)\n\nSimilar to `setTraceFunction()` but automatically applied to all queries.\n\n```js\nmquery.setTraceFunction(traceFunction);\n```\n\n### mquery.canMerge(conditions)\n\nDetermines if `conditions` can be merged using `mquery().merge()`.\n\n```js\nvar query = mquery({ type: 'drum' });\nvar okToMerge = mquery.canMerge(anObject)\nif (okToMerge) {\n  query.merge(anObject);\n}\n```\n\n## mquery.use$geoWithin\n\nMongoDB 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.\n\nIf you are running MongoDB \u003c 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`.\n\n```js\nmquery.use$geoWithin = false;\n```\n\n## Custom Base Queries\n\nOften 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.\n\n```js\nvar greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor();\n\n// use it!\nconst n = await greatMovies().count();\nconsole.log('There are %d great movies', n);\n\nconst docs = await greatMovies().where({ name: /^Life/ }).select('name').find();\nconsole.log(docs);\n```\n\n## Validation\n\nMethod 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.\n\n## Debug support\n\nDebug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable:\n\n```sh\nDEBUG=mquery node yourprogram.js\n```\n\nRead the debug module documentation for more details.\n\n## General compatibility\n\n### ObjectIds\n\n`mquery` clones query arguments before passing them to a `collection` method for execution.\nThis prevents accidental side-affects to the objects you pass.\nTo clone `ObjectIds` we need to make some assumptions.\n\nFirst, to check if an object is an `ObjectId`, we check its constructors name. If it matches either\n`ObjectId` or `ObjectID` we clone it.\n\nTo clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall\nback to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the\nNode.js driver, that the `ObjectId` instance has a public `id` property and that\nwhen creating an `ObjectId` instance we can pass that `id` as an argument.\n\n#### Read Preferences\n\n`mquery` supports specifying [Read Preferences](https://www.mongodb.com/docs/manual/core/read-preference/) to control from which MongoDB node your query will read.\nThe Read Preferences spec also support specifying tags. To pass tags, some\ndrivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags.\nIf 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.\n\n## Future goals\n\n- mongo shell compatibility\n- browser compatibility\n\n## Installation\n\n```sh\nnpm install mquery\n```\n\n## License\n\n[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE)\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongoosejs%2Fmquery","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmongoosejs%2Fmquery","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongoosejs%2Fmquery/lists"}