-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
4071 lines (3683 loc) · 114 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { nonenumerable } from "nonenumerable";
type CollectionNamespace = { collection: string };
type CollectionInfo = { namespace: CollectionNamespace };
type Collection = { s: CollectionInfo };
type MixedCollectionName = string | Collection;
type Binary<N extends number = number> = string & {
readonly BinaryStringLength: unique symbol;
length: N;
};
type ObjectExpression = { [k: string]: any } | string;
/**
* A valid expression, string, number, boolean or null.
*/
type Expression = ObjectExpression | number | boolean;
/**
* A number or any valid expression that resolves to a number.
*/
type NumberExpression = ObjectExpression | number | string;
/**
* An array or any valid expression that resolves to an array.
*/
type ArrayExpression = ObjectExpression | Array<any> | string;
/**
* A string or any valid expression that resolves to a string.
*/
type StringExpression = ObjectExpression | Array<any> | string;
/**
* A date or any valid expression that resolves to a date.
*/
type DateExpression = ObjectExpression | Date | string;
type ArrayOfExpressions = Array<ObjectExpression>;
type Timestamp = number;
// always two
const at = (ns: string) => (...args: any[]) => {
if (args.length !== 2) {
throw new TypeError(`${ns} expects two arguments. Received ${args.length} arguments.`);
}
const [a1, a2] = args;
return { [ns]: [a1, a2] };
};
// pass thru args (as array)
const pta = (ns: string) => (...args: any[]) => ({ [ns]: args });
// pass thru args (or first arg as array)
const ptafaa = (ns: string) => (...args: any[]) => ({ [ns]: args.length === 1 && Array.isArray(args) ? args[0] : args });
// no expression
const ne = (ns: string) => () => ({ [ns]: {} });
// single expression
const se = (ns: string, validate?: (ns: string, expr: Expression) => void) => (expr: Expression) => {
if (validate) validate(ns, expr);
return { [ns]: expr };
};
// [dynamic] two or one arguments indicate varied application in drive
const taf = (ns: string) => (...args: any[]) => {
if (args.length > 1) {
return { [ns]: args };
}
return { [ns]: args[0] };
};
const onlyOnce = (subject: { [k: string]: any }, methodName: string) => {
const subjectText = subject.constructor.name;
if (subject[methodName] === undefined) {
throw new Error(`Method name "${methodName}" does not exist on ${subjectText}`);
}
if (typeof subject[methodName] !== 'function') {
throw new Error(`The ${methodName} method is not a function on ${subjectText}`);
}
Object.defineProperty(subject, methodName, {
value: function() {
throw new Error(`Redundant call to ${methodName}() on ${subjectText} not allowed.`);
},
});
};
const validateFieldExpression = (ns: string, v: any) => {
const type = typeof v;
if (type === 'object') {
if (Object.getPrototypeOf(v) !== Object.getPrototypeOf({})) {
const name = v.constructor.name || 'unknown';
throw new Error(`Expression for ${ns} expected to be a plain object. Received ${name}`);
}
if (Object.keys(v).length <= 0) {
throw new Error(`Expression for ${ns} cannot be an empty object`);
}
} else {
throw new TypeError(`Expression for ${ns} expected to be an object. Received: ${type}`);
}
};
const getCollectionName = (v: MixedCollectionName) => {
if (typeof v === 'string') {
return v;
}
if (v.s && v.s.namespace && typeof v.s.namespace.collection === 'string') {
return v.s.namespace.collection;
}
throw new TypeError(`Invalid $lookup from parameter: ${v}`);
};
type OperatorFn = (...args: any[]) => ObjectExpression;
const safeNumberArgs = (fn: OperatorFn) => (...args: any[]) => {
const nums = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
return fn(...nums.map((arg) => {
switch (typeof arg) {
case 'boolean':
return arg ? 1 : 0;
case 'number':
return arg;
case 'string':
if (arg.match(/^[^$]/)) return 0;
break;
case 'object':
if (arg === null) return 0;
break;
case 'undefined':
return 0;
default:
}
return $ifNull(arg, 0);
}));
};
type PipelineStage = Expression;
// Allow easier syntax for conditional stages in pipeline.
const pipeline = (...args: PipelineStage[]) => args.filter((v) => v).map((v) => {
return typeof v === 'function' ? v(v) : v;
});
/**
* STAGES
*/
type AddFieldsStage = { $addFields: ObjectExpression };
/**
* Adds new fields to documents.
* @category Stages
* @function
* @param {ObjectExpression} expression Specify the name of each field to add
* and set its value to an aggregation expression or an empty object.
* @returns {AddFieldsStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/addFields/|MongoDB reference}
* for $addFields
* @example
* $addFields({ fullName: $.concat('$firstName', ' ', '$lastName') });
* // returns
* { $addFields: { fullName: { $concat: ['$firstName', ' ', '$lastName'] } } }
*/
const $addFields = se('$addFields', validateFieldExpression);
type BaseBucketExpression = {
groupBy: Expression,
output: ObjectExpression,
};
type BucketExpression = BaseBucketExpression & {
boundaries: Array<number>,
default: Expression,
};
class Bucket {
public $bucket: Partial<BucketExpression> = {};
constructor(
groupBy: Expression,
boundaries?: Array<number>,
defaultId?: Expression,
output?: ObjectExpression,
) {
this.groupBy(groupBy);
if (boundaries) {
this.boundaries(...boundaries);
}
if (defaultId) {
this.default(defaultId);
}
if (output) {
this.output(output);
}
}
groupBy(value: Expression) {
this.$bucket.groupBy = value;
onlyOnce(this, 'groupBy');
return this;
}
output(document: ObjectExpression) {
this.$bucket.output = document;
onlyOnce(this, 'output');
return this;
}
default(value: Expression) {
this.$bucket.default = value;
onlyOnce(this, 'default');
return this;
}
boundaries(...args: Array<number>) {
this.$bucket.boundaries = args;
onlyOnce(this, 'boundaries');
return this;
}
}
/**
* Categorizes incoming documents into groups called buckets, based on a
* specified expression and bucket boundaries.
* @category Stages
* @function
* @param {Expression} groupBy An expression to group documents by.
* @param {Array<number>} [boundaries] An array of values based on the groupBy
* expression that specify the boundaries for each bucket.
* @param {Expression} [defaultId] Optional. A literal that specifies the _id of
* an additional bucket that contains all documents that don't fall into a
* bucket specified by boundaries.
* @param {ObjectExpression} output Optional. A document that specifies the
* fields to include.
* @returns {Bucket} A Bucket object populated according to argument input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket/|MongoDB reference}
* for $bucket
* @example <caption>Static notation</caption>
* $bucket('$price', [0, 200, 400], 'Other');
* // outputs
* { $bucket: { groupBy: '$price', boundaries: [0, 200, 400], default: 'Other' } }
* @example <caption>Object notation</caption>
* $bucket('$price').boundaries(0, 200, 400).default('Other');
* // outputs
* { $bucket: { groupBy: '$price', boundaries: [0, 200, 400], default: 'Other' } }
*/
const $bucket = (
groupBy: Expression,
boundaries?: Array<number>,
defaultId?: Expression,
output?: ObjectExpression,
) => new Bucket(groupBy, boundaries, defaultId, output);
type BucketAutoExpression = BaseBucketExpression & {
buckets: number,
granularity: string,
};
class BucketAuto {
public $bucketAuto: Partial<BucketAutoExpression> = {};
constructor(
groupBy: Expression,
buckets?: number,
granularity?: string,
output?: ObjectExpression,
) {
this.groupBy(groupBy);
if (buckets) {
this.buckets(buckets);
}
if (granularity) {
this.granularity(granularity);
}
if (output) {
this.output(output);
}
}
groupBy(value: Expression) {
this.$bucketAuto.groupBy = value;
onlyOnce(this, 'groupBy');
return this;
}
output(document: ObjectExpression) {
this.$bucketAuto.output = document;
onlyOnce(this, 'output');
return this;
}
buckets(value: number) {
this.$bucketAuto.buckets = value;
onlyOnce(this, 'buckets');
return this;
}
granularity(value: string) {
this.$bucketAuto.granularity = value;
onlyOnce(this, 'granularity');
return this;
}
}
/**
* Categorizes incoming documents into a specific number of groups, called
* buckets, based on a specified expression.
* @category Stages
* @function
* @param {Expression} groupBy An expression to group documents by.
* @param {number} [buckets] A positive number for the number of buckets into
* which input documents will be grouped.
* expression that specify the boundaries for each bucket.
* @param {string} [granularity] Optional. Specifies the preferred number series
* to use.
* @param {ObjectExpression} [output] Optional. A document that specifies the
* fields to include.
* @returns {Bucket} A Bucket object populated according to argument input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketAuto/|MongoDB reference}
* for $bucketAuto
* @example <caption>Static notation</caption>
* $bucketAuto('$_id', 5);
* // returns
* { $bucketAuto: { groupBy: '$_id', buckets: 5 } }
* @example <caption>Object notation</caption>
* $bucketAuto('$_id').buckets(5).granularity('R5');
* // returns
* { $bucketAuto: { groupBy: '$_id', buckets: 5, granularity: 'R5' } }
*/
const $bucketAuto = (
groupBy: Expression,
buckets?: number,
granularity?: string,
output?: ObjectExpression,
) => new BucketAuto(groupBy, buckets, granularity, output);
enum ChangeStreamFullDocument {
default,
required,
updateLookup,
whenAvailable,
}
enum ChangeStreamFullDocumentBeforeChange {
off,
whenAvailable,
required,
}
type ChangeStreamExpression = {
allChangesForCluster?: boolean,
fullDocument?: ChangeStreamFullDocument,
fullDocumentBeforeChange?: ChangeStreamFullDocumentBeforeChange,
resumeAfter?: number,
showExpandedEvents?: boolean,
startAfter?: ObjectExpression,
startAtOperationTime?: Timestamp,
};
class ChangeStream {
public $changeStream: ChangeStreamExpression = {};
constructor(opts: ChangeStreamExpression = {}) {
if (opts.allChangesForCluster) this.allChangesForCluster(opts.allChangesForCluster);
if (opts.fullDocument) this.fullDocument(opts.fullDocument);
if (opts.fullDocumentBeforeChange) this.fullDocumentBeforeChange(opts.fullDocumentBeforeChange);
if (opts.resumeAfter) this.resumeAfter(opts.resumeAfter);
if (opts.showExpandedEvents) this.showExpandedEvents(opts.showExpandedEvents);
if (opts.startAfter) this.startAfter(opts.startAfter);
if (opts.startAtOperationTime) this.startAtOperationTime(opts.startAtOperationTime);
// Object.entries(opts).forEach(([opt, val]) => this[opt as keyof ChangeStreamExpression](val));
// Object.entries(opts).forEach(([opt, val]) => this[opt as keyof ChangeStreamExpression](val));
}
allChangesForCluster(value: boolean) {
this.$changeStream.allChangesForCluster = value;
onlyOnce(this, 'allChangesForCluster');
return this;
}
fullDocument(value: ChangeStreamFullDocument) {
this.$changeStream.fullDocument = value;
onlyOnce(this, 'fullDocument');
return this;
}
fullDocumentBeforeChange(value: ChangeStreamFullDocumentBeforeChange) {
this.$changeStream.fullDocumentBeforeChange = value;
onlyOnce(this, 'fullDocument');
return this;
}
resumeAfter(value: number) {
this.$changeStream.resumeAfter = value;
onlyOnce(this, 'resumeAfter');
return this;
}
showExpandedEvents(value: boolean) {
this.$changeStream.showExpandedEvents = value;
onlyOnce(this, 'showExpandedEvents');
return this;
}
startAfter(value: ObjectExpression) {
this.$changeStream.startAfter = value;
onlyOnce(this, 'startAfter');
return this;
}
startAtOperationTime(value: Timestamp) {
this.$changeStream.startAtOperationTime = value;
onlyOnce(this, 'startAtOperationTime');
return this;
}
}
/**
* Returns a Change Stream cursor on a collection, a database, or an entire
* cluster. Must be the first stage in the pipeline.
* @category Stages
* @function
* @param {ChangeStreamExpression} [opts] Change stream options.
* @returns {ChangeStream} A ChangeStream instance populated according to
* argument input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/changeStream/|MongoDB reference}
* for $changeStream
* @example <caption>Basic example</caption>
* $changeStream();
* // returns
* { $changeStream: {} }
*/
const $changeStream = (opts?: ChangeStreamExpression) => new ChangeStream(opts)
type CountOperator = {
$count: string,
};
/**
* Passes a document to the next stage that contains a count of the number of
* documents input to the stage.
* @category Stages
* @function
* @param {string} [name] The name of the output field for the count value.
* Must be a non-empty string, must not start with `$` nor contain `.`.
* @returns {CountOperator} A $count operator expression.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/addFields/|MongoDB reference}
* for $addFields
* @example
* $count('myCount');
* // returns
* { $count: 'myCount' }
* @example <caption>Use default name "count"</caption>
* $count();
* // returns
* { $count: "count" }
*/
const $count = (name = 'count') => ({ $count: name });
type DocumentsStage = {
$documents: ObjectExpression;
};
/**
* Returns literal documents from input values.
* @category Stages
* @function
* @param {ObjectExpression | Array<ObjectExpression>} mixed The first document
* or an array of documents.
* @param {...ObjectExpression[]} [args] Additional documents to input into the
* pipeline.
* @returns {DocumentsStage} Returns a $document operator based on input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents/|MongoDB reference}
* for $documents
* @example
* $documents({ x: 10 }, { x: 2 }, { x: 5 });
* // returns
* { $documents: [{ x: 10 }, { x: 2 }, { x: 5 }
*/
const $documents = (mixed: ObjectExpression | Array<ObjectExpression>, ...args: ObjectExpression[]) => {
let documents;
if (Array.isArray(mixed)) {
documents = mixed as Array<ObjectExpression>;
} else {
documents = args.length ? [mixed, ...args] : [mixed];
}
return { $documents: documents };
};
type FacetExpression = { [k: string]: Array<PipelineStage> };
type FacetStage = { $facet: FacetExpression };
/**
* Processes multiple aggregation pipelines within a single stage on the same
* set of input documents.
* @category Stages
* @function
* @param {FacetExpression} expression Refer to documentation.
* @returns {FacetStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/project/|MongoDB reference}
* for $project
* @example
* $project({ x: '$y' });
* // returns
* { $project: { x: '$y' } }
*/
const $facet = se('$facet');
type GroupStage = {
$group: ObjectExpression,
};
/**
* Separates documents into groups according to a "group key".
* @category Stages
* @function
* @param {ObjectExpression} expression Refer to documentation.
* @returns {GroupStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/group/|MongoDB reference}
* for $group
* @example
* $group({ _id: '$userId', total: $sum(1)) });
* // returns
* { $group: { _id: '$userId', total: { $sum: 1 } } };
*/
const $group = se('$group');
type LimitStage = {
$limit: number,
};
/**
* Limits the number of documents passed to the next stage in the pipeline.
* @category Stages
* @function
* @param {number} value A positive 64bit integer.
* @returns {LimitStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit/|MongoDB reference}
* for $limit
* @example
* $limit(10);
* // returns
* { $limit: 10 }
*/
const $limit = se('$limit');
type LookupExpression = {
from: string;
as: string;
localField?: string;
foreignField?: string;
let?: Expression;
pipeline?: PipelineStage[];
};
class Lookup {
public $lookup: Partial<LookupExpression> = {};
public constructor(
from: MixedCollectionName | Array<ObjectExpression>,
as: string,
localField?: string,
foreignField?: string
) {
if (Array.isArray(from)) {
this.$lookup.pipeline = [$documents(...from as [ObjectExpression, ...ObjectExpression[]])];
} else {
this.from(from);
}
this.as(as);
if (localField) this.localField(localField);
if (foreignField) this.foreignField(foreignField);
}
from(v: MixedCollectionName) {
this.$lookup.from = getCollectionName(v);
onlyOnce(this, 'from');
return this;
}
as(v: string) {
this.$lookup.as = v;
onlyOnce(this, 'as');
return this;
}
localField(v: string) {
this.$lookup.localField = v;
onlyOnce(this, 'localField');
return this;
}
foreignField(v: string) {
this.$lookup.foreignField = v;
onlyOnce(this, 'foreignField');
return this;
}
let(v: Expression) {
this.$lookup.let = v;
onlyOnce(this, 'let');
return this;
}
pipeline(...args: PipelineStage[]) {
let stages;
if (args.length === 1 && Array.isArray(args[0])) {
[stages] = args;
} else {
stages = args;
}
if (this.$lookup.pipeline === undefined) {
this.$lookup.pipeline = stages as PipelineStage[];
} else {
this.$lookup.pipeline.push(...stages as PipelineStage[]);
}
onlyOnce(this, 'pipeline');
return this;
}
}
/**
* Performs a left outer join to a collection in the same database adding a new
* array field to each input document.
* @category Stages
* @function
* @param {MixedCollectionName | Array<ObjectExpression>} from Specifies the collection in the same
* database to perform the join with. Can be either the collection name or the
* Collection object.
* @param {string} [asName] Specifies the name of the new array field to add to
* the input documents where the results of the lookup will be.
* @param {string} [localField] Specifies the field from the documents input to
* the lookup stage.
* @param {string} [foreignField] Specifies the field in the from collection the documents input to
* the lookup stage.
* @returns {Lookup} A Lookup instance populated based on argument input that
* contains the relevant methods for otherwise configuring a $lookup stage.
* @example <caption>Common lookup</caption>
* $lookup('myCollection', 'myVar', 'localId', 'foreignId');
* // returns a Lookup object populated like:
* { $lookup: { from: 'myCollection', as: 'myVar', localField: 'localId', foreignField: 'foreignId' } }
* @example <caption>Lookup with $documents in pipeline</caption>
* // Pass the documents as an array using the "from" argument
* $lookup([{ k: 1 }, { k: 2 }], 'subdocs')
* .let({ key: '$docKey' })
* .pipeline($.match({ k: '$$key' }));
* // returns a Lookup object populated as follows:
* {
* $lookup: {
* as: 'subdocs',
* let: { localField: '$docKey' },
* pipeline: [
* { $documents: [{ k: 1 }, { k: 2 }] },
* { $match: { k: '$$localField' } },
* ],
* },
* }
*/
const $lookup = (
from: MixedCollectionName | Array<ObjectExpression>,
asName: string,
localField?: string,
foreignField?: string,
) => new Lookup(from, asName, localField, foreignField);
type MatchStage = {
$match: ObjectExpression,
};
/**
* Filters the documents to pass only the documents that match the specified
* conditions(s) to the next pipeline stage.
* @category Stages
* @function
* @param {ObjectExpression} fieldExpression
* @returns {MatchStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/match/|MongoDB reference}
* for $match
* @example
* $match({ x: 1 });
* // returns
* { $match: { x: 1 } },
*/
const $match = se('$match');
type DatabaseAndCollectionName = {
db: string,
coll: MixedCollectionName,
};
/**
* @typedef {string} MergeActionWhenMatched
* @description Enumeration of: Replace (replace), KeepExisting (keepExisting), Merge
* (merge), Fail (fail) and Pipeline (pipeline).
*/
enum MergeActionWhenMatched {
Replace = 'replace',
KeepExisting = 'keepExisting',
Merge = 'merge',
Fail = 'fail',
Pipeline = 'pipeline',
}
/**
* @typedef {string} MergeActionWhenNotMatched
* @description Enumeration of: Insert (insert), Discard (discard) or Fail
* (fail).
*/
enum MergeActionWhenNotMatched {
Insert = 'insert',
Discard = 'discard',
Fail = 'fail',
}
type MergeExpression = {
into: string | DatabaseAndCollectionName,
let?: Expression,
on?: Expression,
whenMatched?: MergeActionWhenMatched,
whenNotMatched?: MergeActionWhenNotMatched,
};
class Merge {
$merge: MergeExpression;
constructor(into: MixedCollectionName, onExpr?: Expression) {
this.$merge = { into: getCollectionName(into) };
if (onExpr) this.on(onExpr);
}
on(onExpression: Expression) {
this.$merge.on = onExpression;
onlyOnce(this, 'on');
return this;
}
let(varsExpression: Expression) {
this.$merge.let = varsExpression;
onlyOnce(this, 'let');
return this;
}
whenMatched(action: MergeActionWhenMatched) {
this.$merge.whenMatched = action;
onlyOnce(this, 'whenMatched');
return this;
}
whenNotMatched(action: MergeActionWhenNotMatched) {
this.$merge.whenNotMatched = action;
onlyOnce(this, 'whenNotMatched');
return this;
}
}
/**
* Writes the results of the pipeline to a specified location. Must be the last
* stage in the pipeline.
* @category Stages
* @function
* @param {MixedCollectionName | DatabaseAndCollectionName} into The collectionName or Collection object to
* merge into.
* @param {string|Array<string>} [onExpr] Field or fields that act as a unique
* identifier for the document.
* @returns {Merge} Returns a Merge object populated according to the provided
* arguments.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/project/|MongoDB reference}
* for $project
* @example <caption>On single-field</caption>
* $merge('myCollection', 'key');
* // returns
* { $merge: { into: 'myCollection', on: 'key' } }
* @example <caption>On multiple fields</caption>
* $merge('myCollection', ['key1', 'key2']);
* { $merge: { into: 'myCollection', on: ['key1', 'key2'] } }
* @example <caption>Full example</caption>
* $merge('myCollection', ['key1', 'key2'])
* .whenMatched('replace')
* .whenNotMatched('discard');
* @todo Add support for accepting a pipleine for whenMatched.
*/
const $merge = (into: MixedCollectionName, onExpr?: string | Array<string>) => new Merge(into, onExpr);
type OutExpression = string | DatabaseAndCollectionName;
/**
* @category Stages
* @param {MixedCollectionName} collection The collection name or Collection object
* to output to.
* @param {string} [db] The output database name.
* @returns {OutExpression} An $out expression accoring to argument input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/out/|MongoDB reference}
* for $out
* @example <caption>Basic</caption>
* $out('myCollection');
* // returns
* { $out: 'myCollection' }
* @example <caption>With db</caption>
* $out('myCollection', 'myDb');
* // returns
* { $out: { coll: 'myCollection', db: 'myDb' } }
*/
const $out = (collection: MixedCollectionName, db?: string) => {
if (db) return { $out: { db, coll: getCollectionName(collection) } };
return { $out: collection };
};
type ProjectStage = {
$project: ObjectExpression,
};
/**
* Passes along the documents with the specified fields to the next stage in
* the pipeline.
* @category Stages
* @function
* @param {ObjectExpression} expression Refer to documentation.
* @returns {ProjectStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/project/|MongoDB reference}
* for $project
* @example
* $project({ x: '$y' });
* // returns
* { $project: { x: '$y' } }
*/
const $project = se('$project');
class Redaction {
$redact: Condition;
constructor(ifExpr: Expression, thenExpr?: Expression, elseExpr?: Expression) {
this.$redact = new Condition(ifExpr, thenExpr, elseExpr);
}
then(thenExpr: Expression) {
this.$redact.then(thenExpr);
return this;
}
else(elseExpr: Expression) {
this.$redact.else(elseExpr);
return this;
}
}
/**
* Restricts entire documents or content within documents from being outputted
* based on information stored in the documents themselves.
* @category Stages
* @function
* @param {Expression} ifExpr Any valid expression as long as it resolves to
* a boolean.
* @param {Expression} thenExpr Any valid expression as long as it resolves to
* the $$DESCEND, $$PRUNE, or $$KEEP system variables.
* @param {Expression} elseExpr Any valid expression as long as it resolves to
* the $$DESCEND, $$PRUNE, or $$KEEP system variables.
* @returns {Redaction} Returns a Redaction object that resembles the $redact
* stage whose usage varies based on optional argument input.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/redact/|MongoDB reference}
* for $redact
* @example <caption>Static Notation</caption>
* $redact('$isAdmin', '$$KEEP', '$$PRUNE');
* @example <caption>Object Notation</caption>
* $redact('$isAdmin').then('$$KEEP').else('$$PRUNE');
* @todo Expand for supporting sub-syntax like: `$redact().cond(...`
* @todo Support non-$cond expression
*/
const $redact = (ifExpr: Expression, thenExpr?: Expression, elseExpr?: Expression) => new Redaction(ifExpr, thenExpr, elseExpr);
type ReplaceRootStage = {
$replaceRoot: {
newRoot: string | ObjectExpression,
},
};
/**
* Replaces the input document with the specified document.
* @category Stages
* @function
* @param {string | ObjectExpression} newRoot The replacement document can be any valid express
* @returns {ReplaceRootStage} Returns a $replaceRoot operator stage.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/replaceRoot/|MongoDB reference}
* for $replaceRoot
* @example
* $replaceRoot('$subpath');
* // returns
* { $replaceRoot: { newRoot: '$subpath' } }
*/
const $replaceRoot = (newRoot: string | ObjectExpression) => ({ $replaceRoot: { newRoot } });
type ReplaceWithStage = { $replaceWith: ObjectExpression };
/**
* Replaces the input document with the specified document.
* @category Stages
* @function
* @param {string | ObjectExpression} replacementDocument The replacement
* document can be any valid express
* @returns {ReplaceWithStage} Returns a $replaceWith operator stage.
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/replaceWith/|MongoDB reference}
* for $replaceWith
* @example
* $replaceWith('$subpath');
* // returns
* { $replaceWith: '$subpath' }
*/
const $replaceWith = (replacementDocument: string | ObjectExpression) => ({ $replaceWith: replacementDocument });
type SetStage = { $set: ObjectExpression };
/**
* Adds new fields to documents. (alias of $addFields)
* @category Stages
* @function
* @param {ObjectExpression} expression Specify the name of each field to add
* and set its value to an aggregation expression or an empty object.
* @returns {SetStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/set/|MongoDB reference}
* for $set
* @example
* $set({ fullName: $.concat('$firstName', ' ', '$lastName') });
* // returns { $set: { fullName: { $concat: ['$firstName', ' ', '$lastName'] } } }
*/
const $set = se('$set', validateFieldExpression);
type SkipStage = {
$skip: number,
};
/**
* Skips over the specified number of documents that pass into the stage and
* passes the remaining documents to the next stage in the pipeline.
* @category Stages
* @function
* @param {number} value The number of documents to skip.
* @returns {SkipStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/skip/|MongoDB reference}
* for $skip
* @example
* $skip(10);
* // returns
* { $skip: 10 }
*/
const $skip = se('$skip');
type SortStage = {
$sort: ObjectExpression,
};
/**
* Sorts all input documents and returns them to the pipeline in sorted order.
* @category Stages
* @function
* @param {Expression} expression Refer to documentation.
* @returns {SortStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort/|MongoDB reference}
* for $sort
* @example
* $sort({ x: 1 });
* // returns
* { $sort: { x: 1 } }
*/
const $sort = se('$sort');
type SortByCountStage = {
$sortByCount: ObjectExpression,
};
/**
* Groups incoming documents based on the value of a specified expression, then
* computes the count of documents in each distinct group.
* @category Stages
* @function
* @param {Expression} expression Refer to documentation.
* @returns {SortByCountStage}
* @see {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount/|MongoDB reference}
* for $sortByCount
* @example
* $sortByCount('$employee');
* // returns
* { $sortByCount: '$employee' }
*/
const $sortByCount = se('$sortByCount');
type UnwindExpression = {
path: string;
preserveNullAndEmptyArrays?: boolean;
includeArrayIndex?: string;
};
class Unwind {
@nonenumerable
params: UnwindExpression;
get path() {
return this.params.path;
}