-
Notifications
You must be signed in to change notification settings - Fork 4
/
collection.ts
1760 lines (1597 loc) · 60.1 KB
/
collection.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
// Copyright DataStax, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { normalizeSort, takeWhile } from './utils';
import { FindCursor } from '@/src/data-api/cursor';
import { Db, SomeDoc, SomeId } from '@/src/data-api';
import {
BulkWriteError,
CollectionNotFoundError,
DataAPIResponseError,
DeleteManyError,
InsertManyError,
mkRespErrorFromResponse,
mkRespErrorFromResponses,
TooManyDocumentsToCountError,
UpdateManyError,
} from '@/src/data-api/errors';
import objectHash from 'object-hash';
import { DataAPIHttpClient } from '@/src/api';
import {
AnyBulkWriteOperation,
BulkWriteOptions,
BulkWriteResult,
CollectionOptions,
DeleteManyResult,
DeleteOneOptions,
DeleteOneResult,
Filter,
FindOneAndDeleteOptions,
FindOneAndReplaceOptions,
FindOneAndUpdateOptions,
FindOneOptions,
FindOptions,
Flatten,
FoundDoc,
IdOf,
InsertManyOptions,
InsertManyResult,
InsertOneOptions,
InsertOneResult,
MaybeId,
ModifyResult,
NoId,
ReplaceOneOptions,
ReplaceOneResult,
ToDotNotation,
UpdateFilter,
UpdateManyOptions,
UpdateManyResult,
UpdateOneOptions,
UpdateOneResult,
WithId,
} from '@/src/data-api/types';
import { TimeoutManager } from '@/src/api/timeout-managers';
import { WithTimeout } from '@/src/common/types';
import { DeleteManyCommand } from '@/src/data-api/types/delete/delete-many';
import { FindOneCommand } from '@/src/data-api/types/find/find-one';
import { InsertOneCommand } from '@/src/data-api/types/insert/insert-one';
import { UpdateOneCommand } from '@/src/data-api/types/update/update-one';
import { UpdateManyCommand } from '@/src/data-api/types/update/update-many';
import { FindOneAndReplaceCommand } from '@/src/data-api/types/find/find-one-replace';
import { DeleteOneCommand } from '@/src/data-api/types/delete/delete-one';
import { FindOneAndDeleteCommand } from '@/src/data-api/types/find/find-one-delete';
import { FindOneAndUpdateCommand } from '@/src/data-api/types/find/find-one-update';
import { InsertManyCommand } from '@/src/data-api/types/insert/insert-many';
import { Mutable } from '@/src/data-api/types/utils';
/**
* Represents the interface to a collection in the database.
*
* **Shouldn't be directly instantiated, but rather created via {@link Db.createCollection},
* or connected to using {@link Db.collection}**.
*
* Typed as `Collection<Schema>` where `Schema` is the type of the documents in the collection.
* Operations on the collection will be strongly typed if a specific schema is provided, otherwise
* remained largely weakly typed if no type is provided, which may be preferred for dynamic data
* access & operations.
*
* @example
* ```typescript
* const collection = await db.createCollection<PersonSchema>('my_collection');
* await collection.insertOne({ _id: '1', name: 'John Doe' });
* await collection.drop();
* ```
*
* @see SomeDoc
* @see VectorDoc
*
* @public
*/
export class Collection<Schema extends SomeDoc = SomeDoc> {
private readonly _httpClient!: DataAPIHttpClient;
private readonly _db!: Db
/**
* The name of the collection.
*/
public readonly collectionName!: string;
/**
* The namespace (aka keyspace) that the collection lives in.
*/
public readonly namespace!: string;
/**
* Use {@link Db.collection} to obtain an instance of this class.
*
* @internal
*/
constructor(db: Db, httpClient: DataAPIHttpClient, name: string, namespace: string | undefined) {
Object.defineProperty(this, 'collectionName', {
value: name,
writable: false,
});
Object.defineProperty(this, 'namespace', {
value: namespace ?? db.namespace,
writable: false,
});
Object.defineProperty(this, '_httpClient', {
value: httpClient.withCollection(this.namespace, this.collectionName),
enumerable: false,
});
Object.defineProperty(this, '_db', {
value: db,
enumerable: false,
});
}
/**
* Inserts a single document into the collection atomically.
*
* If the document does not contain an `_id` field, the server will generate an id for the document. The type of the
* id may be specified in {@link CollectionOptions.defaultId} at creation, otherwise it'll just be a UUID string. This
* generation will not mutate the documents.
*
* If an `_id` is provided which corresponds to a document that already exists in the collection, an error is raised,
* and the insertion fails.
*
* See {@link InsertOneOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* // Insert a document with a specific ID
* await collection.insertOne({ _id: '1', name: 'John Doe' });
*
* // Insert a document with an autogenerated ID
* await collection.insertOne({ name: 'Jane Doe' });
*
* // Insert a document with a vector
* await collection.insertOne({ name: 'Jane Doe' }, { vector: [.12, .52, .32] });
* await collection.insertOne({ name: 'Jane Doe', $vector: [.12, .52, .32] });
* ```
*
* @param document - The document to insert.
* @param options - The options for this operation.
*
* @returns The result of the operation.
*/
public async insertOne(document: MaybeId<Schema>, options?: InsertOneOptions): Promise<InsertOneResult<Schema>> {
const command: InsertOneCommand = {
insertOne: { document },
}
if (options?.vector && options?.vectorize) {
throw new Error('Cannot set both vector and vectorize options');
}
if (options?.vector) {
command.insertOne.document = { ...command.insertOne.document, $vector: options.vector };
}
if (options?.vectorize) {
command.insertOne.document = { ...command.insertOne.document, $vectorize: options.vectorize };
}
const resp = await this._httpClient.executeCommand(command, options);
return {
insertedId: resp.status?.insertedIds[0],
};
}
/**
* Inserts many documents into the collection.
*
* **NB. This function paginates the insertion of documents in chunks to avoid running into insertion limits. This
* means multiple requests may be made to the server, and the operation may not be atomic.**
*
* If any document does not contain an `_id` field, the server will generate an id for the document. The type of the
* id may be specified in {@link CollectionOptions.defaultId} at creation, otherwise it'll just be a UUID string. This
* generation will not mutate the documents.
*
* You may set the `ordered` option to `true` to stop the operation after the first error; otherwise all documents
* may be parallelized and processed in arbitrary order, improving, perhaps vastly, performance.
*
* You can set the `concurrency` option to control how many network requests are made in parallel on unordered
* insertions. Defaults to `8`.
*
* If a 2XX insertion error occurs, the operation will throw an {@link InsertManyError} containing the partial result.
*
* See {@link InsertManyOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* try {
* await collection.insertMany([
* { _id: '1', name: 'John Doe' },
* { name: 'Jane Doe' },
* ], { ordered: true });
*
* await collection.insertMany([
* { _id: '1', name: 'John Doe', $vector: [.12, .52, .32] },
* { name: 'Jane Doe', $vector: [.32, .52, .12] },
* ]);
*
* await collection.insertMany([
* { _id: '1', name: 'John Doe' },
* { name: 'Jane Doe' },
* ], {
* vectors: [
* [.12, .52, .32],
* [.32, .52, .12],
* ],
* ordered: true,
* });
* } catch (e) {
* if (e instanceof InsertManyError) {
* console.log(e.insertedIds);
* }
* }
* ```
*
* @remarks
* This operation is not atomic. Depending on the amount of inserted documents, and if it's ordered or not, it can
* keep running (in a blocking way) for a macroscopic amount of time. In that case, new documents that are inserted
* from another concurrent process/application may be inserted during the execution of this method call, and if there
* are duplicate keys, it's not easy to predict which application will win the race.
*
* --
*
* *If a thrown exception is not due to an insertion error, e.g. a `5xx` error or network error, the operation will throw the
* underlying error.*
*
* *In case of an unordered request, if the error was a simple insertion error, a `InsertManyError` will be thrown
* after every document has been attempted to be inserted. If it was a `5xx` or similar, the error will be thrown
* immediately.*
*
* @param documents - The documents to insert.
* @param options - The options for this operation.
*
* @returns The aggregated result of the operation.
*
* @throws InsertManyError - If the operation fails.
*/
public async insertMany(documents: MaybeId<Schema>[], options?: InsertManyOptions): Promise<InsertManyResult<Schema>> {
const chunkSize = options?.chunkSize ?? 20;
if (options?.vectors) {
if (options.vectors.length !== documents.length) {
throw new Error('The number of vectors must match the number of documents');
}
for (let i = 0, n = documents.length; i < n; i++) {
if (options.vectors[i]) {
documents[i] = { ...documents[i], $vector: options.vectors[i] };
}
}
}
if (options?.vectorize) {
if (options.vectorize.length !== documents.length) {
throw new Error('The number of vectors must match the number of documents');
}
for (let i = 0, n = documents.length; i < n; i++) {
if (options.vectorize[i]) {
if (documents[i].$vector) {
throw new Error('Vector and vectorize options cannot overlap');
}
documents[i] = { ...documents[i], $vectorize: options.vectorize[i] };
}
}
}
const timeoutManager = this._httpClient.timeoutManager(options?.maxTimeMS);
const insertedIds = (options?.ordered)
? await insertManyOrdered<Schema>(this._httpClient, documents, chunkSize, timeoutManager)
: await insertManyUnordered<Schema>(this._httpClient, documents, options?.concurrency ?? 8, chunkSize, timeoutManager);
return {
insertedCount: insertedIds.length,
insertedIds: insertedIds,
}
}
/**
* Atomically updates a single document in the collection.
*
* If `upsert` is set to true, it will insert the document if no match is found.
*
* You can also specify a sort option to determine which document to update if multiple documents match the filter.
*
* See {@link UpdateOneOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* // Update by ID
* await collection.insertOne({ _id: '1', name: 'John Doe' });
*
* await collection.updateOne(
* { _id: '1' },
* { $set: { name: 'Jane Doe' }
* });
*
* // Update by vector search
* await collection.insertOne({ name: 'John Doe', $vector: [.12, .52, .32] });
*
* await collection.updateOne(
* {},
* { $set: { name: 'Jane Doe' } },
* { vector: [.09, .58, .21] }
* );
*
* await collection.updateOne(
* {},
* { $set: { name: 'Jane Doe' } },
* { sort: { $vector: [.09, .58, .21] } }
* );
* ```
*
* @param filter - A filter to select the document to update.
* @param update - The update to apply to the selected document.
* @param options - The options for this operation.
*
* @returns The result of the operation.
*
* @see StrictFilter
* @see StrictUpdateFilter
*/
public async updateOne(filter: Filter<Schema>, update: UpdateFilter<Schema>, options?: UpdateOneOptions): Promise<UpdateOneResult<Schema>> {
options = coalesceVectorSpecialsIntoSort(options);
const command: UpdateOneCommand = {
updateOne: {
filter,
update,
options: {
upsert: options?.upsert,
},
},
};
if (options?.sort) {
command.updateOne.sort = normalizeSort(options.sort);
}
const resp = await this._httpClient.executeCommand(command, options);
const commonResult = {
modifiedCount: resp.status?.modifiedCount,
matchedCount: resp.status?.matchedCount,
};
return (resp.status?.upsertedId)
? {
...commonResult,
upsertedId: resp.status?.upsertedId,
upsertedCount: 1,
}
: {
...commonResult,
upsertedCount: 0,
};
}
/**
* Updates many documents in the collection.
*
* **NB. This function paginates the updating of documents in chunks to avoid running into insertion limits. This
* means multiple requests may be made to the server, and the operation may not be atomic.**
*
* If `upsert` is set to true, it will insert a document if no match is found.
*
* You can also specify a sort option to determine which documents to update if multiple documents match the filter.
*
* See {@link UpdateManyOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* await collection.insertMany([
* { _id: '1', name: 'John Doe', car: 'Renault Twizy' },
* { _id: UUID.v4(), name: 'Jane Doe' },
* { name: 'Dane Joe' },
* ]);
*
* // Will give 'Jane' and 'Dane' a car 'unknown'
* await collection.updateMany({
* car: { $exists: false },
* }, {
* $set: { car: 'unknown' },
* });
*
* // Will upsert a document with name 'Anette' and car 'Volvo v90'
* await collection.updateMany({
* name: 'Anette',
* }, {
* $set: { car: 'Volvo v90' },
* }, {
* upsert: true,
* });
* ```
*
* @remarks
* This operation is not atomic. Depending on the amount of matching documents, it can keep running (in a blocking
* way) for a macroscopic amount of time. In that case, new documents that are inserted from another concurrent process/
* application at the same time may be updated during the execution of this method call. In other words, it cannot
* easily be predicted whether a given newly-inserted document will be picked up by the updateMany command or not.
*
* @param filter - A filter to select the documents to update.
* @param update - The update to apply to the selected documents.
* @param options - The options for this operation.
*
* @returns The aggregated result of the operation.
*
* @see StrictFilter
* @see StrictUpdateFilter
*/
public async updateMany(filter: Filter<Schema>, update: UpdateFilter<Schema>, options?: UpdateManyOptions): Promise<UpdateManyResult<SomeDoc>> {
const command: UpdateManyCommand = {
updateMany: {
filter,
update,
options: {
upsert: options?.upsert,
},
},
};
const timeoutManager = this._httpClient.timeoutManager(options?.maxTimeMS);
const commonResult = {
modifiedCount: 0,
matchedCount: 0,
upsertedCount: 0 as const,
};
let resp;
try {
while (!resp || resp.status?.nextPageState) {
resp = await this._httpClient.executeCommand(command, { timeoutManager });
command.updateMany.options.pagingState = resp.status?.nextPageState ;
commonResult.modifiedCount += resp.status?.modifiedCount ?? 0;
commonResult.matchedCount += resp.status?.matchedCount ?? 0;
}
} catch (e) {
if (!(e instanceof DataAPIResponseError)) {
throw e;
}
const desc = e.detailedErrorDescriptors[0];
commonResult.modifiedCount += desc.rawResponse?.status?.modifiedCount ?? 0;
commonResult.matchedCount += desc.rawResponse?.status?.matchedCount ?? 0;
commonResult.upsertedCount = desc.rawResponse?.status?.upsertedCount ?? 0;
throw mkRespErrorFromResponse(UpdateManyError, command, desc.rawResponse, commonResult);
}
return (resp.status?.upsertedId)
? {
...commonResult,
upsertedId: resp.status?.upsertedId,
upsertedCount: 1,
}
: commonResult;
}
/**
* Replaces a single document in the collection.
*
* If `upsert` is set to true, it will insert the replacement regardless of if no match is found.
*
* See {@link ReplaceOneOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* await collection.insertOne({
* _id: '1',
* name: 'John Doe',
* $vector: [.12, .52, .32],
* });
*
* // Replace by ID
* await collection.replaceOne({ _id: '1' }, { name: 'Jane Doe' });
*
* // Replace by name
* await collection.replaceOne({
* name: 'John Doe',
* }, {
* name: 'Jane Doe',
* });
*
* // Replace by vector
* await collection.replaceOne({}, {
* name: 'Jane Doe'
* }, {
* vector: [.09, .58, .22],
* });
*
* // Upsert if no match
* await collection.replaceOne({
* name: 'Lynyrd Skynyrd',
* }, {
* name: 'Lenerd Skinerd',
* }, {
* upsert: true,
* });
* ```
*
* @param filter - A filter to select the document to replace.
* @param replacement - The replacement document, which contains no `_id` field.
* @param options - The options for this operation.
*
* @returns The result of the operation.
*
* @see StrictFilter
*/
public async replaceOne(filter: Filter<Schema>, replacement: NoId<Schema>, options?: ReplaceOneOptions): Promise<ReplaceOneResult<Schema>> {
options = coalesceVectorSpecialsIntoSort(options);
const command: FindOneAndReplaceCommand = {
findOneAndReplace: {
filter,
replacement,
options: {
returnDocument: 'before',
upsert: options?.upsert,
},
// projection: { '*': 0 },
},
};
if (options?.sort) {
command.findOneAndReplace.sort = normalizeSort(options.sort);
}
const resp = await this._httpClient.executeCommand(command, options);
const commonResult = {
modifiedCount: resp.status?.modifiedCount,
matchedCount: resp.status?.matchedCount,
};
return (resp.status?.upsertedId)
? {
...commonResult,
upsertedId: resp.status?.upsertedId,
upsertedCount: 1,
}
: {
...commonResult,
upsertedCount: 0,
};
}
/**
* Atomically deletes a single document from the collection.
*
* You can specify a `sort` option to determine which document to delete if multiple documents match the filter.
*
* See {@link DeleteOneOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* // Delete by _id
* await collection.insertOne({ _id: '1', name: 'John Doe' });
* await collection.deleteOne({ _id: '1' });
*
* // Delete by name
* await collection.insertOne({ name: 'Jane Doe', age: 25 });
* await collection.insertOne({ name: 'Jane Doe', age: 33 });
* await collection.deleteOne({ name: 'Jane Doe' }, { sort: { age: -1 } });
*
* // Delete by vector
* await collection.insertOne({ name: 'Jane Doe', $vector: [.12, .52, .32] });
* await collection.deleteOne({}, { vector: [.09, .58, .42] });
* ```
*
* @param filter - A filter to select the document to delete.
* @param options - The options for this operation.
*
* @returns The result of the operation.
*
* @see StrictFilter
*/
public async deleteOne(filter: Filter<Schema> = {}, options?: DeleteOneOptions): Promise<DeleteOneResult> {
options = coalesceVectorSpecialsIntoSort(options);
const command: DeleteOneCommand = {
deleteOne: { filter },
};
if (options?.sort) {
command.deleteOne.sort = normalizeSort(options.sort);
}
const deleteOneResp = await this._httpClient.executeCommand(command, options);
return {
deletedCount: deleteOneResp.status?.deletedCount,
};
}
/**
* Deletes many documents from the collection.
*
* **NB. This function paginates the deletion of documents in chunks to avoid running into insertion limits. This
* means multiple requests may be made to the server, and the operation may not be atomic.**
*
* If an empty filter is passed, an error will be thrown, asking you to use {@link Collection.deleteAll} instead for your safety.
*
* @example
* ```typescript
* await collection.insertMany([
* { _id: '1', name: 'John Doe' },
* { name: 'John Doe' },
* ]);
*
* await collection.deleteMany({ name: 'John Doe' });
* ```
*
* @remarks
* This operation is not atomic. Depending on the amount of matching documents, it can keep running (in a blocking
* way) for a macroscopic amount of time. In that case, new documents that are inserted from another concurrent process/
* application at the same time may be deleted during the execution of this method call. In other words, it cannot
* easily be predicted whether a given newly-inserted document will be picked up by the deleteMany command or not.
*
* @param filter - A filter to select the documents to delete.
* @param options - The options for this operation.
*
* @returns The aggregated result of the operation.
*
* @throws Error - If an empty filter is passed.
*
* @see StrictFilter
*/
public async deleteMany(filter: Filter<Schema> = {}, options?: WithTimeout): Promise<DeleteManyResult> {
if (Object.keys(filter).length === 0) {
throw new Error('Can\'t pass an empty filter to deleteMany, use deleteAll instead if you really want to delete everything');
}
const command: DeleteManyCommand = {
deleteMany: { filter },
};
const timeoutManager = this._httpClient.timeoutManager(options?.maxTimeMS);
let resp;
let numDeleted = 0;
try {
while (!resp || resp.status?.moreData) {
resp = await this._httpClient.executeCommand(command, { timeoutManager });
numDeleted += resp.status?.deletedCount ?? 0;
}
} catch (e) {
if (!(e instanceof DataAPIResponseError)) {
throw e;
}
const desc = e.detailedErrorDescriptors[0];
throw mkRespErrorFromResponse(DeleteManyError, command, desc.rawResponse, { deletedCount: numDeleted + (desc.rawResponse?.status?.deletedCount ?? 0) })
}
return {
deletedCount: numDeleted,
};
}
/**
* Deletes all documents from the collection.
*
* Unlike {@link Collection.deleteMany}, this method is atomic and will delete all documents in the collection in one go,
* without making multiple network requests to the server.
*
* @remarks Use with caution. Wear a helmet. Don't say I didn't warn you.
*
* @param options - The options for this operation.
*
* @returns A promise that resolves when the operation is complete.
*/
public async deleteAll(options?: WithTimeout): Promise<void> {
const command: DeleteManyCommand = {
deleteMany: { filter: {} },
};
await this._httpClient.executeCommand(command, options);
}
/**
* Find documents on the collection, optionally matching the provided filter.
*
* Also accepts `sort`, `limit`, `skip`, `includeSimilarity`, and `projection` options.
*
* The method returns a {@link FindCursor} that can then be iterated over.
*
* **NB. If a *non-vector-sort* `sort` option is provided, the iteration of all documents may not be atomic**—it will
* iterate over cursors in an approximate way, exhibiting occasional skipped or duplicate documents, with real-time
* collection insertions/mutations being displayed.
*
* See {@link FindOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* await collection.insertMany([
* { name: 'John Doe' },
* { name: 'Jane Doe' },
* { name: 'Dane Joe' },
* ], {
* vectors: [
* [.12, .52, .32],
* [.32, .52, .12],
* [.52, .32, .12],
* ],
* });
*
* // Find by name
* const cursor1 = collection.find({ name: 'John Doe' });
*
* // Returns ['John Doe']
* console.log(await cursor1.toArray());
*
* // Match all docs, sorting by name
* const cursor2 = collection.find({}, {
* sort: { name: 1 },
* });
*
* // Returns 'Dane Joe', 'Jane Doe', 'John Doe'
* for await (const doc of cursor2) {
* console.log(doc);
* }
*
* // Find by vector
* const cursor3 = collection.find({}, {
* vector: [.12, .52, .32],
* });
*
* // Returns 'John Doe'
* console.log(await cursor3.next());
* ```
*
* @remarks
* Some combinations of arguments impose an implicit upper bound on the number of documents that are returned by the
* Data API. Namely:
*
* (a) Vector ANN searches cannot return more than a number of documents
* that at the time of writing is set to 1000 items.
*
* (b) When using a sort criterion of the ascending/descending type,
* the Data API will return a smaller number of documents, set to 20
* at the time of writing, and stop there. The returned documents are
* the top results across the whole collection according to the requested
* criterion.
*
* --
*
* When not specifying sorting criteria at all (by vector or otherwise),
* the cursor can scroll through an arbitrary number of documents as
* the Data API and the client periodically exchange new chunks of documents.
* It should be noted that the behavior of the cursor in the case documents
* have been added/removed after the `find` was started depends on database
* internals, and it is not guaranteed, nor excluded, that such "real-time"
* changes in the data would be picked up by the cursor.
*
* @param filter - A filter to select the documents to find. If not provided, all documents will be returned.
* @param options - The options for this operation.
*
* @returns A FindCursor which can be iterated over.
*
* @see StrictFilter
*/
find(filter: Filter<Schema>, options?: FindOptions): FindCursor<FoundDoc<Schema>, FoundDoc<Schema>> {
return new FindCursor(this.namespace, this._httpClient, filter as any, coalesceVectorSpecialsIntoSort(options)) as any;
}
/**
* Return a list of the unique values of `key` across the documents in the collection that match the provided filter.
*
* **NB. This is a *client-side* operation**—this effectively browses all matching documents (albeit with a
* projection) using the logic of the {@link Collection.find} method, and collects the unique value for the
* given `key` manually. As such, there may be performance, latency and ultimately billing implications if the
* amount of matching documents is large.
*
* The key may use dot-notation to access nested fields, such as `'field'`, `'field.subfield'`, `'field.3'`,
* `'field.3.subfield'`, etc. If lists are encountered and no numeric index is specified, all items in the list are
* pulled.
*
* **Note that on complex extractions, the return type may be not as expected.** In that case, it's on the user to
* cast the return type to the correct one.
*
* Distinct works with arbitrary objects as well, by creating a deterministic hash of the object and comparing it
* with the hashes of the objects already seen. This, unsurprisingly, may not be great for performance if you have
* a lot of records that match, so it's recommended to use distinct on simple values whenever performance or number
* of records is a concern.
*
* For details on the behaviour of "distinct" in conjunction with real-time changes in the collection contents, see
* the remarks on the `find` command.
*
* @example
* ```typescript
* await collection.insertMany([
* { letter: { value: 'a' }, car: [1] },
* { letter: { value: 'b' }, car: [2, 3] },
* { letter: { value: 'a' }, car: [2], bus: 'no' },
* ]);
*
* // ['a', 'b']
* const distinct = await collection.distinct('letter.value');
*
* await collection.insertOne({
* x: [{ y: 'Y', 0: 'ZERO' }],
* });
*
* // ['Y']
* await collection.distinct('x.y');
*
* // [{ y: 'Y', 0: 'ZERO' }]
* await collection.distinct('x.0');
*
* // ['Y']
* await collection.distinct('x.0.y');
*
* // ['ZERO']
* await collection.distinct('x.0.0');
* ```
*
* @param key - The dot-notation key to pick which values to retrieve unique
* @param filter - A filter to select the documents to find. If not provided, all documents will be matched.
*
* @returns A list of all the unique values selected by the given `key`
*
* @see StrictFilter
*/
public async distinct<Key extends string>(key: Key, filter: Filter<Schema> = {}): Promise<Flatten<(SomeDoc & ToDotNotation<FoundDoc<Schema>>)[Key]>[]> {
assertPathSafe4Distinct(key);
const projection = pullSafeProjection4Distinct(key);
const cursor = this.find(filter, { projection: { _id: 0, [projection]: 1 } });
const seen = new Set<unknown>();
const ret = [];
const extract = mkDistinctPathExtractor(key);
for await (const doc of cursor) {
const values = extract(doc);
for (let i = 0, n = values.length; i < n; i++) {
if (typeof values[i] === 'object') {
const hash = objectHash(values[i]);
if (!seen.has(hash)) {
seen.add(hash);
ret.push(values[i]);
}
} else {
if (!seen.has(values[i])) {
seen.add(values[i]);
ret.push(values[i]);
}
}
}
}
return ret;
}
/**
* Finds a single document in the collection, if it exists.
*
* You can specify a `sort` option to determine which document to find if multiple documents match the filter.
*
* You can also specify a `projection` option to determine which fields to include in the returned document.
*
* If performing a vector search, you can set the `includeSimilarity` option to `true` to include the similarity score
* in the returned document as `$similarity: number`.
*
* See {@link FindOneOptions} for complete information about the options available for this operation.
*
* @example
* ```typescript
* const doc1 = await collection.findOne({
* name: 'John Doe',
* });
*
* // Will be undefined
* console.log(doc1?.$similarity);
*
* const doc2 = await collection.findOne({}, {
* sort: {
* $vector: [.12, .52, .32],
* },
* includeSimilarity: true,
* });
*
* // Will be a number
* console.log(doc2?.$similarity);
* ```
*
* @remarks
* If you really need `limit` or `skip`, prefer using the {@link Collection.find} method instead.
*
* @param filter - A filter to select the document to find.
* @param options - The options for this operation.
*
* @returns The found document, or `null` if no document was found.
*
* @see StrictFilter
*/
public async findOne(filter: Filter<Schema>, options?: FindOneOptions): Promise<FoundDoc<Schema> | null> {
options = coalesceVectorSpecialsIntoSort(options);
const command: FindOneCommand = {
findOne: {
filter,
options: {
includeSimilarity: options?.includeSimilarity,
}
},
};
if (options?.sort) {
command.findOne.sort = normalizeSort(options.sort);
}
if (options?.projection && Object.keys(options.projection).length > 0) {
command.findOne.projection = options.projection;
}
const resp = await this._httpClient.executeCommand(command, options);
return resp.data?.document;
}
/**
* Counts the number of documents in the collection, optionally with a filter.
*
* Takes in a `limit` option which dictates the maximum number of documents that may be present before a
* {@link TooManyDocumentsToCountError} is thrown. If the limit is higher than the highest limit accepted by the
* Data API, a {@link TooManyDocumentsToCountError} will be thrown anyway (i.e. `1000`).
*
* @example
* ```typescript
* await collection.insertMany([
* { _id: '1', name: 'John Doe' },
* { name: 'Jane Doe' },
* ]);
*
* const count = await collection.countDocuments({ name: 'John Doe' }, 1000);
* console.log(count); // 1
*
* // Will throw a TooManyDocumentsToCountError as it counts 1, but the limit is 0
* const count = await collection.countDocuments({ name: 'John Doe' }, 0);
* ```
*
* @remarks
* Count operations are expensive: for this reason, the best practice is to provide a reasonable `upperBound`
* according to the caller expectations. Moreover, indiscriminate usage of count operations for sizeable amounts
* of documents (i.e. in the thousands and more) is discouraged in favor of alternative application-specific
* solutions. Keep in mind that the Data API has a hard upper limit on the amount of documents it will count,
* and that an exception will be thrown by this method if this limit is encountered.
*
* @param filter - A filter to select the documents to count. If not provided, all documents will be counted.
* @param upperBound - The maximum number of documents to count.
* @param options - The options for this operation.
*
* @returns The number of counted documents, if below the provided limit
*
* @throws TooManyDocumentsToCountError - If the number of documents counted exceeds the provided limit.
*
* @see StrictFilter
*/
public async countDocuments(filter: Filter<Schema>, upperBound: number, options?: WithTimeout): Promise<number> {
const command = {
countDocuments: { filter },
};