Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
```js
// 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 }]);
mquery(..).read(preference).exec();
```
Read 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).
### readConcern()
Sets the readConcern option for the query.
```js
// local
mquery().readConcern('local')
mquery().readConcern('l')
mquery().r('l')
// available
mquery().readConcern('available')
mquery().readConcern('a')
mquery().r('a')
// majority
mquery().readConcern('majority')
mquery().readConcern('m')
mquery().r('m')
// linearizable
mquery().readConcern('linearizable')
mquery().readConcern('lz')
mquery().r('lz')
// snapshot
mquery().readConcern('snapshot')
mquery().readConcern('s')
mquery().r('s')
```
##### Read Concern Level:
- `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+)
- `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+)
- `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+)
- `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+)
- `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+)
Aliases
- `l` local
- `a` available
- `m` majority
- `lz` linearizable
- `s` snapshot
Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
### writeConcern()
Sets the writeConcern option for the query.
This option is only valid for operations that write to the database:
- `deleteOne()`
- `deleteMany()`
- `findOneAndDelete()`
- `findOneAndUpdate()`
- `remove()`
- `update()`
- `updateOne()`
- `updateMany()`
```js
mquery().writeConcern(0)
mquery().writeConcern(1)
mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 })
mquery().writeConcern('majority')
mquery().writeConcern('m') // same as majority
mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead
mquery().w(1) // w is alias of writeConcern
```
##### Write Concern:
writeConcern({ w: `<value>`, j: `<boolean>`, wtimeout: `<number>` }`)
- 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
- the j option to request acknowledgement that the write operation has been written to the journal
- the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely
Can be break down to use the following syntax:
mquery().w(`<value>`).j(`<boolean>`).wtimeout(`<number>`)
Read more about how to use write concern [here](https://docs.mongodb.com/manual/reference/write-concern/)
### slaveOk()
Sets the slaveOk option. `true` allows reading from secondaries.
**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2
```js
query.slaveOk() // true
query.slaveOk(true)
query.slaveOk(false)
```
[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/)
### snapshot()
Specifies this query as a snapshot query.
```js
mquery().snapshot() // true
mquery().snapshot(true)
mquery().snapshot(false)
```
_Cannot be used with `distinct()`._
[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/)
### tailable()
Sets tailable option.
```js
mquery().tailable() <== true
mquery().tailable(true)
mquery().tailable(false)
```
_Cannot be used with `distinct()`._
[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/)
### wtimeout()
Specifies a time limit, in milliseconds, for the write concern. If `w > 1`, it is maximum amount of time to
wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout.
This option is only valid for operations that write to the database:
- `deleteOne()`
- `deleteMany()`
- `findOneAndDelete()`
- `findOneAndUpdate()`
- `remove()`
- `update()`
- `updateOne()`
- `updateMany()`
Defaults to `wtimeout` value if it is specified in [writeConcern](#writeconcern)
```js
mquery().wtimeout(2000)
mquery().wTimeout(2000)
```
## Helpers
### collection()
Sets the querys collection.
```js
mquery().collection(aCollection)
```
### then()
Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error.
```js
mquery().find(..).then(success, error);
```
This 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.
```js
co(function*(){
var doc = yield mquery().findOne({ _id: 499 });
console.log(doc); // { _id: 499, name: 'amazing', .. }
})();
```
_NOTE_:
The returned promise is a [bluebird](https://github.com/petkaantonov/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+](http://promisesaplus.com/) compliant.
### thunk()
Returns a thunk which when called runs the query's `exec` method passing the results to the callback.
```js
var thunk = mquery(collection).find({..}).thunk();
thunk(function(err, results) {
})
```
### merge(object)
Merges other mquery or match condition objects into this one. When an mquery instance is passed, its match conditions, field selection and options are merged.
```js
var drum = mquery({ type: 'drum' }).collection(instruments);
var redDrum = mquery({ color: 'red' }).merge(drum);
redDrum.count(function (err, n) {
console.log('there are %d red drums', n);
})
```
Internally uses `mquery.canMerge` to determine validity.
### setOptions(options)
Sets query options.
```js
mquery().setOptions({ collection: coll, limit: 20 })
```
##### options
- [tailable](#tailable) *
- [sort](#sort) *
- [limit](#limit) *
- [skip](#skip) *
- [maxScan](#maxscan) *
- [maxTime](#maxtime) *
- [batchSize](#batchSize) *
- [comment](#comment) *
- [snapshot](#snapshot) *
- [hint](#hint) *
- [collection](#collection): the collection to query against
_* denotes a query helper method is also available_
### setTraceFunction(func)
Set a function to trace this query. Useful for profiling or logging.
```js
function traceFunction (method, queryInfo, query) {
console.log('starting ' + method + ' query');
return function (err, result, millis) {
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.
### mquery.setGlobalTraceFunction(func)
Similar to `setTraceFunction()` but automatically applied to all queries.
```js
mquery.setTraceFunction(traceFunction);
```
### mquery.canMerge(conditions)
Determines if `conditions` can be merged using `mquery().merge()`.
```js
var query = mquery({ type: 'drum' });
var okToMerge = mquery.canMerge(anObject)
if (okToMerge) {
query.merge(anObject);
}
```
## mquery.use$geoWithin
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`.
```js
mquery.use$geoWithin = false;
```
## Custom Base Queries
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.
```js
var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor();
// use it!
greatMovies().count(function (err, n) {
console.log('There are %d great movies', n);
});
greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) {
console.log(docs);
});
```
## Validation
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 support
Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable:
DEBUG=mquery node yourprogram.js
Read the debug module documentation for more details.
## General compatibility
#### ObjectIds
`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(obj.id)`. 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.
#### Read Preferences
`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.
## Future goals
- mongo shell compatibility
- browser compatibility
## Installation
$ npm install mquery
## License
[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE)