UNPKG

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