aggregate.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. 'use strict';
  2. /*!
  3. * Module dependencies
  4. */
  5. const AggregationCursor = require('./cursor/AggregationCursor');
  6. const Query = require('./query');
  7. const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS');
  8. const promiseOrCallback = require('./helpers/promiseOrCallback');
  9. const stringifyFunctionOperators = require('./helpers/aggregate/stringifyFunctionOperators');
  10. const util = require('util');
  11. const utils = require('./utils');
  12. const read = Query.prototype.read;
  13. const readConcern = Query.prototype.readConcern;
  14. /**
  15. * Aggregate constructor used for building aggregation pipelines. Do not
  16. * instantiate this class directly, use [Model.aggregate()](/docs/api.html#model_Model.aggregate) instead.
  17. *
  18. * ####Example:
  19. *
  20. * const aggregate = Model.aggregate([
  21. * { $project: { a: 1, b: 1 } },
  22. * { $skip: 5 }
  23. * ]);
  24. *
  25. * Model.
  26. * aggregate([{ $match: { age: { $gte: 21 }}}]).
  27. * unwind('tags').
  28. * exec(callback);
  29. *
  30. * ####Note:
  31. *
  32. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  33. * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database
  34. *
  35. * ```javascript
  36. * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
  37. * // Do this instead to cast to an ObjectId
  38. * new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);
  39. * ```
  40. *
  41. * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
  42. * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate
  43. * @param {Array} [pipeline] aggregation pipeline as an array of objects
  44. * @api public
  45. */
  46. function Aggregate(pipeline) {
  47. this._pipeline = [];
  48. this._model = undefined;
  49. this.options = {};
  50. if (arguments.length === 1 && util.isArray(pipeline)) {
  51. this.append.apply(this, pipeline);
  52. }
  53. }
  54. /**
  55. * Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/).
  56. * Supported options are:
  57. *
  58. * - `readPreference`
  59. * - [`cursor`](./api.html#aggregate_Aggregate-cursor)
  60. * - [`explain`](./api.html#aggregate_Aggregate-explain)
  61. * - [`allowDiskUse`](./api.html#aggregate_Aggregate-allowDiskUse)
  62. * - `maxTimeMS`
  63. * - `bypassDocumentValidation`
  64. * - `raw`
  65. * - `promoteLongs`
  66. * - `promoteValues`
  67. * - `promoteBuffers`
  68. * - [`collation`](./api.html#aggregate_Aggregate-collation)
  69. * - `comment`
  70. * - [`session`](./api.html#aggregate_Aggregate-session)
  71. *
  72. * @property options
  73. * @memberOf Aggregate
  74. * @api public
  75. */
  76. Aggregate.prototype.options;
  77. /**
  78. * Get/set the model that this aggregation will execute on.
  79. *
  80. * ####Example:
  81. * const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
  82. * aggregate.model() === MyModel; // true
  83. *
  84. * // Change the model. There's rarely any reason to do this.
  85. * aggregate.model(SomeOtherModel);
  86. * aggregate.model() === SomeOtherModel; // true
  87. *
  88. * @param {Model} [model] the model to which the aggregate is to be bound
  89. * @return {Aggregate|Model} if model is passed, will return `this`, otherwise will return the model
  90. * @api public
  91. */
  92. Aggregate.prototype.model = function(model) {
  93. if (arguments.length === 0) {
  94. return this._model;
  95. }
  96. this._model = model;
  97. if (model.schema != null) {
  98. if (this.options.readPreference == null &&
  99. model.schema.options.read != null) {
  100. this.options.readPreference = model.schema.options.read;
  101. }
  102. if (this.options.collation == null &&
  103. model.schema.options.collation != null) {
  104. this.options.collation = model.schema.options.collation;
  105. }
  106. }
  107. return this;
  108. };
  109. /**
  110. * Appends new operators to this aggregate pipeline
  111. *
  112. * ####Examples:
  113. *
  114. * aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
  115. *
  116. * // or pass an array
  117. * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
  118. * aggregate.append(pipeline);
  119. *
  120. * @param {Object} ops operator(s) to append
  121. * @return {Aggregate}
  122. * @api public
  123. */
  124. Aggregate.prototype.append = function() {
  125. const args = (arguments.length === 1 && util.isArray(arguments[0]))
  126. ? arguments[0]
  127. : utils.args(arguments);
  128. if (!args.every(isOperator)) {
  129. throw new Error('Arguments must be aggregate pipeline operators');
  130. }
  131. this._pipeline = this._pipeline.concat(args);
  132. return this;
  133. };
  134. /**
  135. * Appends a new $addFields operator to this aggregate pipeline.
  136. * Requires MongoDB v3.4+ to work
  137. *
  138. * ####Examples:
  139. *
  140. * // adding new fields based on existing fields
  141. * aggregate.addFields({
  142. * newField: '$b.nested'
  143. * , plusTen: { $add: ['$val', 10]}
  144. * , sub: {
  145. * name: '$a'
  146. * }
  147. * })
  148. *
  149. * // etc
  150. * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
  151. *
  152. * @param {Object} arg field specification
  153. * @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/
  154. * @return {Aggregate}
  155. * @api public
  156. */
  157. Aggregate.prototype.addFields = function(arg) {
  158. const fields = {};
  159. if (typeof arg === 'object' && !util.isArray(arg)) {
  160. Object.keys(arg).forEach(function(field) {
  161. fields[field] = arg[field];
  162. });
  163. } else {
  164. throw new Error('Invalid addFields() argument. Must be an object');
  165. }
  166. return this.append({ $addFields: fields });
  167. };
  168. /**
  169. * Appends a new $project operator to this aggregate pipeline.
  170. *
  171. * Mongoose query [selection syntax](#query_Query-select) is also supported.
  172. *
  173. * ####Examples:
  174. *
  175. * // include a, include b, exclude _id
  176. * aggregate.project("a b -_id");
  177. *
  178. * // or you may use object notation, useful when
  179. * // you have keys already prefixed with a "-"
  180. * aggregate.project({a: 1, b: 1, _id: 0});
  181. *
  182. * // reshaping documents
  183. * aggregate.project({
  184. * newField: '$b.nested'
  185. * , plusTen: { $add: ['$val', 10]}
  186. * , sub: {
  187. * name: '$a'
  188. * }
  189. * })
  190. *
  191. * // etc
  192. * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
  193. *
  194. * @param {Object|String} arg field specification
  195. * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/
  196. * @return {Aggregate}
  197. * @api public
  198. */
  199. Aggregate.prototype.project = function(arg) {
  200. const fields = {};
  201. if (typeof arg === 'object' && !util.isArray(arg)) {
  202. Object.keys(arg).forEach(function(field) {
  203. fields[field] = arg[field];
  204. });
  205. } else if (arguments.length === 1 && typeof arg === 'string') {
  206. arg.split(/\s+/).forEach(function(field) {
  207. if (!field) {
  208. return;
  209. }
  210. const include = field[0] === '-' ? 0 : 1;
  211. if (include === 0) {
  212. field = field.substring(1);
  213. }
  214. fields[field] = include;
  215. });
  216. } else {
  217. throw new Error('Invalid project() argument. Must be string or object');
  218. }
  219. return this.append({ $project: fields });
  220. };
  221. /**
  222. * Appends a new custom $group operator to this aggregate pipeline.
  223. *
  224. * ####Examples:
  225. *
  226. * aggregate.group({ _id: "$department" });
  227. *
  228. * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/
  229. * @method group
  230. * @memberOf Aggregate
  231. * @instance
  232. * @param {Object} arg $group operator contents
  233. * @return {Aggregate}
  234. * @api public
  235. */
  236. /**
  237. * Appends a new custom $match operator to this aggregate pipeline.
  238. *
  239. * ####Examples:
  240. *
  241. * aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
  242. *
  243. * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/
  244. * @method match
  245. * @memberOf Aggregate
  246. * @instance
  247. * @param {Object} arg $match operator contents
  248. * @return {Aggregate}
  249. * @api public
  250. */
  251. /**
  252. * Appends a new $skip operator to this aggregate pipeline.
  253. *
  254. * ####Examples:
  255. *
  256. * aggregate.skip(10);
  257. *
  258. * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/
  259. * @method skip
  260. * @memberOf Aggregate
  261. * @instance
  262. * @param {Number} num number of records to skip before next stage
  263. * @return {Aggregate}
  264. * @api public
  265. */
  266. /**
  267. * Appends a new $limit operator to this aggregate pipeline.
  268. *
  269. * ####Examples:
  270. *
  271. * aggregate.limit(10);
  272. *
  273. * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/
  274. * @method limit
  275. * @memberOf Aggregate
  276. * @instance
  277. * @param {Number} num maximum number of records to pass to the next stage
  278. * @return {Aggregate}
  279. * @api public
  280. */
  281. /**
  282. * Appends a new $geoNear operator to this aggregate pipeline.
  283. *
  284. * ####NOTE:
  285. *
  286. * **MUST** be used as the first operator in the pipeline.
  287. *
  288. * ####Examples:
  289. *
  290. * aggregate.near({
  291. * near: [40.724, -73.997],
  292. * distanceField: "dist.calculated", // required
  293. * maxDistance: 0.008,
  294. * query: { type: "public" },
  295. * includeLocs: "dist.location",
  296. * uniqueDocs: true,
  297. * num: 5
  298. * });
  299. *
  300. * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/
  301. * @method near
  302. * @memberOf Aggregate
  303. * @instance
  304. * @param {Object} arg
  305. * @return {Aggregate}
  306. * @api public
  307. */
  308. Aggregate.prototype.near = function(arg) {
  309. const op = {};
  310. op.$geoNear = arg;
  311. return this.append(op);
  312. };
  313. /*!
  314. * define methods
  315. */
  316. 'group match skip limit out'.split(' ').forEach(function($operator) {
  317. Aggregate.prototype[$operator] = function(arg) {
  318. const op = {};
  319. op['$' + $operator] = arg;
  320. return this.append(op);
  321. };
  322. });
  323. /**
  324. * Appends new custom $unwind operator(s) to this aggregate pipeline.
  325. *
  326. * Note that the `$unwind` operator requires the path name to start with '$'.
  327. * Mongoose will prepend '$' if the specified field doesn't start '$'.
  328. *
  329. * ####Examples:
  330. *
  331. * aggregate.unwind("tags");
  332. * aggregate.unwind("a", "b", "c");
  333. * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });
  334. *
  335. * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/
  336. * @param {String|Object} fields the field(s) to unwind, either as field names or as [objects with options](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#document-operand-with-options). If passing a string, prefixing the field name with '$' is optional. If passing an object, `path` must start with '$'.
  337. * @return {Aggregate}
  338. * @api public
  339. */
  340. Aggregate.prototype.unwind = function() {
  341. const args = utils.args(arguments);
  342. const res = [];
  343. for (const arg of args) {
  344. if (arg && typeof arg === 'object') {
  345. res.push({ $unwind: arg });
  346. } else if (typeof arg === 'string') {
  347. res.push({
  348. $unwind: (arg && arg.startsWith('$')) ? arg : '$' + arg
  349. });
  350. } else {
  351. throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
  352. 'must be string or object');
  353. }
  354. }
  355. return this.append.apply(this, res);
  356. };
  357. /**
  358. * Appends a new $replaceRoot operator to this aggregate pipeline.
  359. *
  360. * Note that the `$replaceRoot` operator requires field strings to start with '$'.
  361. * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'.
  362. * If you are passing in an object the strings in your expression will not be altered.
  363. *
  364. * ####Examples:
  365. *
  366. * aggregate.replaceRoot("user");
  367. *
  368. * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });
  369. *
  370. * @see $replaceRoot https://docs.mongodb.org/manual/reference/operator/aggregation/replaceRoot
  371. * @param {String|Object} the field or document which will become the new root document
  372. * @return {Aggregate}
  373. * @api public
  374. */
  375. Aggregate.prototype.replaceRoot = function(newRoot) {
  376. let ret;
  377. if (typeof newRoot === 'string') {
  378. ret = newRoot.startsWith('$') ? newRoot : '$' + newRoot;
  379. } else {
  380. ret = newRoot;
  381. }
  382. return this.append({
  383. $replaceRoot: {
  384. newRoot: ret
  385. }
  386. });
  387. };
  388. /**
  389. * Appends a new $count operator to this aggregate pipeline.
  390. *
  391. * ####Examples:
  392. *
  393. * aggregate.count("userCount");
  394. *
  395. * @see $count https://docs.mongodb.org/manual/reference/operator/aggregation/count
  396. * @param {String} the name of the count field
  397. * @return {Aggregate}
  398. * @api public
  399. */
  400. Aggregate.prototype.count = function(countName) {
  401. return this.append({ $count: countName });
  402. };
  403. /**
  404. * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name
  405. * or a pipeline object.
  406. *
  407. * Note that the `$sortByCount` operator requires the new root to start with '$'.
  408. * Mongoose will prepend '$' if the specified field name doesn't start with '$'.
  409. *
  410. * ####Examples:
  411. *
  412. * aggregate.sortByCount('users');
  413. * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
  414. *
  415. * @see $sortByCount https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/
  416. * @param {Object|String} arg
  417. * @return {Aggregate} this
  418. * @api public
  419. */
  420. Aggregate.prototype.sortByCount = function(arg) {
  421. if (arg && typeof arg === 'object') {
  422. return this.append({ $sortByCount: arg });
  423. } else if (typeof arg === 'string') {
  424. return this.append({
  425. $sortByCount: (arg && arg.startsWith('$')) ? arg : '$' + arg
  426. });
  427. } else {
  428. throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' +
  429. 'must be string or object');
  430. }
  431. };
  432. /**
  433. * Appends new custom $lookup operator to this aggregate pipeline.
  434. *
  435. * ####Examples:
  436. *
  437. * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
  438. *
  439. * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup
  440. * @param {Object} options to $lookup as described in the above link
  441. * @return {Aggregate}* @api public
  442. */
  443. Aggregate.prototype.lookup = function(options) {
  444. return this.append({ $lookup: options });
  445. };
  446. /**
  447. * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.
  448. *
  449. * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified.
  450. *
  451. * #### Examples:
  452. * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
  453. * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites
  454. *
  455. * @see $graphLookup https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup
  456. * @param {Object} options to $graphLookup as described in the above link
  457. * @return {Aggregate}
  458. * @api public
  459. */
  460. Aggregate.prototype.graphLookup = function(options) {
  461. const cloneOptions = {};
  462. if (options) {
  463. if (!utils.isObject(options)) {
  464. throw new TypeError('Invalid graphLookup() argument. Must be an object.');
  465. }
  466. utils.mergeClone(cloneOptions, options);
  467. const startWith = cloneOptions.startWith;
  468. if (startWith && typeof startWith === 'string') {
  469. cloneOptions.startWith = cloneOptions.startWith.startsWith('$') ?
  470. cloneOptions.startWith :
  471. '$' + cloneOptions.startWith;
  472. }
  473. }
  474. return this.append({ $graphLookup: cloneOptions });
  475. };
  476. /**
  477. * Appends new custom $sample operator to this aggregate pipeline.
  478. *
  479. * ####Examples:
  480. *
  481. * aggregate.sample(3); // Add a pipeline that picks 3 random documents
  482. *
  483. * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample
  484. * @param {Number} size number of random documents to pick
  485. * @return {Aggregate}
  486. * @api public
  487. */
  488. Aggregate.prototype.sample = function(size) {
  489. return this.append({ $sample: { size: size } });
  490. };
  491. /**
  492. * Appends a new $sort operator to this aggregate pipeline.
  493. *
  494. * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
  495. *
  496. * 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.
  497. *
  498. * ####Examples:
  499. *
  500. * // these are equivalent
  501. * aggregate.sort({ field: 'asc', test: -1 });
  502. * aggregate.sort('field -test');
  503. *
  504. * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/
  505. * @param {Object|String} arg
  506. * @return {Aggregate} this
  507. * @api public
  508. */
  509. Aggregate.prototype.sort = function(arg) {
  510. // TODO refactor to reuse the query builder logic
  511. const sort = {};
  512. if (arg.constructor.name === 'Object') {
  513. const desc = ['desc', 'descending', -1];
  514. Object.keys(arg).forEach(function(field) {
  515. // If sorting by text score, skip coercing into 1/-1
  516. if (arg[field] instanceof Object && arg[field].$meta) {
  517. sort[field] = arg[field];
  518. return;
  519. }
  520. sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
  521. });
  522. } else if (arguments.length === 1 && typeof arg === 'string') {
  523. arg.split(/\s+/).forEach(function(field) {
  524. if (!field) {
  525. return;
  526. }
  527. const ascend = field[0] === '-' ? -1 : 1;
  528. if (ascend === -1) {
  529. field = field.substring(1);
  530. }
  531. sort[field] = ascend;
  532. });
  533. } else {
  534. throw new TypeError('Invalid sort() argument. Must be a string or object.');
  535. }
  536. return this.append({ $sort: sort });
  537. };
  538. /**
  539. * Sets the readPreference option for the aggregation query.
  540. *
  541. * ####Example:
  542. *
  543. * Model.aggregate(..).read('primaryPreferred').exec(callback)
  544. *
  545. * @param {String} pref one of the listed preference options or their aliases
  546. * @param {Array} [tags] optional tags for this query
  547. * @return {Aggregate} this
  548. * @api public
  549. * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
  550. * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
  551. */
  552. Aggregate.prototype.read = function(pref, tags) {
  553. if (!this.options) {
  554. this.options = {};
  555. }
  556. read.call(this, pref, tags);
  557. return this;
  558. };
  559. /**
  560. * Sets the readConcern level for the aggregation query.
  561. *
  562. * ####Example:
  563. *
  564. * Model.aggregate(..).readConcern('majority').exec(callback)
  565. *
  566. * @param {String} level one of the listed read concern level or their aliases
  567. * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/
  568. * @return {Aggregate} this
  569. * @api public
  570. */
  571. Aggregate.prototype.readConcern = function(level) {
  572. if (!this.options) {
  573. this.options = {};
  574. }
  575. readConcern.call(this, level);
  576. return this;
  577. };
  578. /**
  579. * Appends a new $redact operator to this aggregate pipeline.
  580. *
  581. * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively
  582. * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`.
  583. *
  584. * ####Example:
  585. *
  586. * Model.aggregate(...)
  587. * .redact({
  588. * $cond: {
  589. * if: { $eq: [ '$level', 5 ] },
  590. * then: '$$PRUNE',
  591. * else: '$$DESCEND'
  592. * }
  593. * })
  594. * .exec();
  595. *
  596. * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
  597. * Model.aggregate(...)
  598. * .redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND')
  599. * .exec();
  600. *
  601. * @param {Object} expression redact options or conditional expression
  602. * @param {String|Object} [thenExpr] true case for the condition
  603. * @param {String|Object} [elseExpr] false case for the condition
  604. * @return {Aggregate} this
  605. * @see $redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/
  606. * @api public
  607. */
  608. Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) {
  609. if (arguments.length === 3) {
  610. if ((typeof thenExpr === 'string' && !thenExpr.startsWith('$$')) ||
  611. (typeof elseExpr === 'string' && !elseExpr.startsWith('$$'))) {
  612. throw new Error('If thenExpr or elseExpr is string, it must start with $$. e.g. $$DESCEND, $$PRUNE, $$KEEP');
  613. }
  614. expression = {
  615. $cond: {
  616. if: expression,
  617. then: thenExpr,
  618. else: elseExpr
  619. }
  620. };
  621. } else if (arguments.length !== 1) {
  622. throw new TypeError('Invalid arguments');
  623. }
  624. return this.append({ $redact: expression });
  625. };
  626. /**
  627. * Execute the aggregation with explain
  628. *
  629. * ####Example:
  630. *
  631. * Model.aggregate(..).explain(callback)
  632. *
  633. * @param {Function} callback
  634. * @return {Promise}
  635. */
  636. Aggregate.prototype.explain = function(callback) {
  637. const model = this._model;
  638. return promiseOrCallback(callback, cb => {
  639. if (!this._pipeline.length) {
  640. const err = new Error('Aggregate has empty pipeline');
  641. return cb(err);
  642. }
  643. prepareDiscriminatorPipeline(this);
  644. model.hooks.execPre('aggregate', this, error => {
  645. if (error) {
  646. const _opts = { error: error };
  647. return model.hooks.execPost('aggregate', this, [null], _opts, error => {
  648. cb(error);
  649. });
  650. }
  651. this.options.explain = true;
  652. model.collection.
  653. aggregate(this._pipeline, this.options || {}).
  654. explain((error, result) => {
  655. const _opts = { error: error };
  656. return model.hooks.execPost('aggregate', this, [result], _opts, error => {
  657. if (error) {
  658. return cb(error);
  659. }
  660. return cb(null, result);
  661. });
  662. });
  663. });
  664. }, model.events);
  665. };
  666. /**
  667. * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
  668. *
  669. * ####Example:
  670. *
  671. * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
  672. *
  673. * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
  674. * @param {Array} [tags] optional tags for this query
  675. * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
  676. */
  677. Aggregate.prototype.allowDiskUse = function(value) {
  678. this.options.allowDiskUse = value;
  679. return this;
  680. };
  681. /**
  682. * Sets the hint option for the aggregation query (ignored for < 3.6.0)
  683. *
  684. * ####Example:
  685. *
  686. * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)
  687. *
  688. * @param {Object|String} value a hint object or the index name
  689. * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
  690. */
  691. Aggregate.prototype.hint = function(value) {
  692. this.options.hint = value;
  693. return this;
  694. };
  695. /**
  696. * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html).
  697. *
  698. * ####Example:
  699. *
  700. * const session = await Model.startSession();
  701. * await Model.aggregate(..).session(session);
  702. *
  703. * @param {ClientSession} session
  704. * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
  705. */
  706. Aggregate.prototype.session = function(session) {
  707. if (session == null) {
  708. delete this.options.session;
  709. } else {
  710. this.options.session = session;
  711. }
  712. return this;
  713. };
  714. /**
  715. * Lets you set arbitrary options, for middleware or plugins.
  716. *
  717. * ####Example:
  718. *
  719. * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
  720. * agg.options; // `{ allowDiskUse: true }`
  721. *
  722. * @param {Object} options keys to merge into current options
  723. * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
  724. * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation
  725. * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation)
  726. * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session)
  727. * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
  728. * @return {Aggregate} this
  729. * @api public
  730. */
  731. Aggregate.prototype.option = function(value) {
  732. for (const key in value) {
  733. this.options[key] = value[key];
  734. }
  735. return this;
  736. };
  737. /**
  738. * Sets the cursor option option for the aggregation query (ignored for < 2.6.0).
  739. * Note the different syntax below: .exec() returns a cursor object, and no callback
  740. * is necessary.
  741. *
  742. * ####Example:
  743. *
  744. * const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
  745. * cursor.eachAsync(function(doc, i) {
  746. * // use doc
  747. * });
  748. *
  749. * @param {Object} options
  750. * @param {Number} options.batchSize set the cursor batch size
  751. * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics)
  752. * @return {Aggregate} this
  753. * @api public
  754. * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html
  755. */
  756. Aggregate.prototype.cursor = function(options) {
  757. if (!this.options) {
  758. this.options = {};
  759. }
  760. this.options.cursor = options || {};
  761. return this;
  762. };
  763. /**
  764. * Sets an option on this aggregation. This function will be deprecated in a
  765. * future release. Use the [`cursor()`](./api.html#aggregate_Aggregate-cursor),
  766. * [`collation()`](./api.html#aggregate_Aggregate-collation), etc. helpers to
  767. * set individual options, or access `agg.options` directly.
  768. *
  769. * Note that MongoDB aggregations [do **not** support the `noCursorTimeout` flag](https://jira.mongodb.org/browse/SERVER-6036),
  770. * if you try setting that flag with this function you will get a "unrecognized field 'noCursorTimeout'" error.
  771. *
  772. * @param {String} flag
  773. * @param {Boolean} value
  774. * @return {Aggregate} this
  775. * @api public
  776. * @deprecated Use [`.option()`](api.html#aggregate_Aggregate-option) instead. Note that MongoDB aggregations do **not** support a `noCursorTimeout` option.
  777. */
  778. Aggregate.prototype.addCursorFlag = util.deprecate(function(flag, value) {
  779. if (!this.options) {
  780. this.options = {};
  781. }
  782. this.options[flag] = value;
  783. return this;
  784. }, 'Mongoose: `Aggregate#addCursorFlag()` is deprecated, use `option()` instead');
  785. /**
  786. * Adds a collation
  787. *
  788. * ####Example:
  789. *
  790. * Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec();
  791. *
  792. * @param {Object} collation options
  793. * @return {Aggregate} this
  794. * @api public
  795. * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate
  796. */
  797. Aggregate.prototype.collation = function(collation) {
  798. if (!this.options) {
  799. this.options = {};
  800. }
  801. this.options.collation = collation;
  802. return this;
  803. };
  804. /**
  805. * Combines multiple aggregation pipelines.
  806. *
  807. * ####Example:
  808. *
  809. * Model.aggregate(...)
  810. * .facet({
  811. * books: [{ groupBy: '$author' }],
  812. * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
  813. * })
  814. * .exec();
  815. *
  816. * // Output: { books: [...], price: [{...}, {...}] }
  817. *
  818. * @param {Object} facet options
  819. * @return {Aggregate} this
  820. * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/
  821. * @api public
  822. */
  823. Aggregate.prototype.facet = function(options) {
  824. return this.append({ $facet: options });
  825. };
  826. /**
  827. * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s
  828. * `$search` stage.
  829. *
  830. * ####Example:
  831. *
  832. * Model.aggregate().
  833. * search({
  834. * text: {
  835. * query: 'baseball',
  836. * path: 'plot'
  837. * }
  838. * });
  839. *
  840. * // Output: [{ plot: '...', title: '...' }]
  841. *
  842. * @param {Object} $search options
  843. * @return {Aggregate} this
  844. * @see $search https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/
  845. * @api public
  846. */
  847. Aggregate.prototype.search = function(options) {
  848. return this.append({ $search: options });
  849. };
  850. /**
  851. * Returns the current pipeline
  852. *
  853. * ####Example:
  854. *
  855. * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]
  856. *
  857. * @return {Array}
  858. * @api public
  859. */
  860. Aggregate.prototype.pipeline = function() {
  861. return this._pipeline;
  862. };
  863. /**
  864. * Executes the aggregate pipeline on the currently bound Model.
  865. *
  866. * ####Example:
  867. *
  868. * aggregate.exec(callback);
  869. *
  870. * // Because a promise is returned, the `callback` is optional.
  871. * const promise = aggregate.exec();
  872. * promise.then(..);
  873. *
  874. * @see Promise #promise_Promise
  875. * @param {Function} [callback]
  876. * @return {Promise}
  877. * @api public
  878. */
  879. Aggregate.prototype.exec = function(callback) {
  880. if (!this._model) {
  881. throw new Error('Aggregate not bound to any Model');
  882. }
  883. const model = this._model;
  884. const collection = this._model.collection;
  885. applyGlobalMaxTimeMS(this.options, model);
  886. if (this.options && this.options.cursor) {
  887. return new AggregationCursor(this);
  888. }
  889. return promiseOrCallback(callback, cb => {
  890. prepareDiscriminatorPipeline(this);
  891. stringifyFunctionOperators(this._pipeline);
  892. model.hooks.execPre('aggregate', this, error => {
  893. if (error) {
  894. const _opts = { error: error };
  895. return model.hooks.execPost('aggregate', this, [null], _opts, error => {
  896. cb(error);
  897. });
  898. }
  899. if (!this._pipeline.length) {
  900. return cb(new Error('Aggregate has empty pipeline'));
  901. }
  902. const options = utils.clone(this.options || {});
  903. collection.aggregate(this._pipeline, options, (error, cursor) => {
  904. if (error) {
  905. const _opts = { error: error };
  906. return model.hooks.execPost('aggregate', this, [null], _opts, error => {
  907. if (error) {
  908. return cb(error);
  909. }
  910. return cb(null);
  911. });
  912. }
  913. cursor.toArray((error, result) => {
  914. const _opts = { error: error };
  915. model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => {
  916. if (error) {
  917. return cb(error);
  918. }
  919. cb(null, result);
  920. });
  921. });
  922. });
  923. });
  924. }, model.events);
  925. };
  926. /**
  927. * Provides promise for aggregate.
  928. *
  929. * ####Example:
  930. *
  931. * Model.aggregate(..).then(successCallback, errorCallback);
  932. *
  933. * @see Promise #promise_Promise
  934. * @param {Function} [resolve] successCallback
  935. * @param {Function} [reject] errorCallback
  936. * @return {Promise}
  937. */
  938. Aggregate.prototype.then = function(resolve, reject) {
  939. return this.exec().then(resolve, reject);
  940. };
  941. /**
  942. * Executes the query returning a `Promise` which will be
  943. * resolved with either the doc(s) or rejected with the error.
  944. * Like [`.then()`](#query_Query-then), but only takes a rejection handler.
  945. *
  946. * @param {Function} [reject]
  947. * @return {Promise}
  948. * @api public
  949. */
  950. Aggregate.prototype.catch = function(reject) {
  951. return this.exec().then(null, reject);
  952. };
  953. /**
  954. * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js
  955. * You do not need to call this function explicitly, the JavaScript runtime
  956. * will call it for you.
  957. *
  958. * ####Example
  959. *
  960. * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
  961. * for await (const doc of agg) {
  962. * console.log(doc.name);
  963. * }
  964. *
  965. * Node.js 10.x supports async iterators natively without any flags. You can
  966. * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
  967. *
  968. * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If
  969. * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
  970. * support async iterators.
  971. *
  972. * @method Symbol.asyncIterator
  973. * @memberOf Aggregate
  974. * @instance
  975. * @api public
  976. */
  977. if (Symbol.asyncIterator != null) {
  978. Aggregate.prototype[Symbol.asyncIterator] = function() {
  979. return this.cursor({ useMongooseAggCursor: true }).
  980. exec().
  981. transformNull().
  982. _transformForAsyncIterator();
  983. };
  984. }
  985. /*!
  986. * Helpers
  987. */
  988. /**
  989. * Checks whether an object is likely a pipeline operator
  990. *
  991. * @param {Object} obj object to check
  992. * @return {Boolean}
  993. * @api private
  994. */
  995. function isOperator(obj) {
  996. if (typeof obj !== 'object') {
  997. return false;
  998. }
  999. const k = Object.keys(obj);
  1000. return k.length === 1 && k.some(key => { return key[0] === '$'; });
  1001. }
  1002. /*!
  1003. * Adds the appropriate `$match` pipeline step to the top of an aggregate's
  1004. * pipeline, should it's model is a non-root discriminator type. This is
  1005. * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
  1006. *
  1007. * @param {Aggregate} aggregate Aggregate to prepare
  1008. */
  1009. Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline;
  1010. function prepareDiscriminatorPipeline(aggregate) {
  1011. const schema = aggregate._model.schema;
  1012. const discriminatorMapping = schema && schema.discriminatorMapping;
  1013. if (discriminatorMapping && !discriminatorMapping.isRoot) {
  1014. const originalPipeline = aggregate._pipeline;
  1015. const discriminatorKey = discriminatorMapping.key;
  1016. const discriminatorValue = discriminatorMapping.value;
  1017. // If the first pipeline stage is a match and it doesn't specify a `__t`
  1018. // key, add the discriminator key to it. This allows for potential
  1019. // aggregation query optimizations not to be disturbed by this feature.
  1020. if (originalPipeline[0] && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) {
  1021. originalPipeline[0].$match[discriminatorKey] = discriminatorValue;
  1022. // `originalPipeline` is a ref, so there's no need for
  1023. // aggregate._pipeline = originalPipeline
  1024. } else if (originalPipeline[0] && originalPipeline[0].$geoNear) {
  1025. originalPipeline[0].$geoNear.query =
  1026. originalPipeline[0].$geoNear.query || {};
  1027. originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue;
  1028. } else if (originalPipeline[0] && originalPipeline[0].$search) {
  1029. if (originalPipeline[1] && originalPipeline[1].$match != null) {
  1030. originalPipeline[1].$match[discriminatorKey] = originalPipeline[1].$match[discriminatorKey] || discriminatorValue;
  1031. } else {
  1032. const match = {};
  1033. match[discriminatorKey] = discriminatorValue;
  1034. originalPipeline.splice(1, 0, { $match: match });
  1035. }
  1036. } else {
  1037. const match = {};
  1038. match[discriminatorKey] = discriminatorValue;
  1039. aggregate._pipeline.unshift({ $match: match });
  1040. }
  1041. }
  1042. }
  1043. /*!
  1044. * Exports
  1045. */
  1046. module.exports = Aggregate;