Newer
Older
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
/// <reference types="node" />
import type { DeserializeOptions , ObjectIdLike , SerializeOptions } from 'bson';
import { Binary , BSON , BSONRegExp , BSONSymbol , BSONType , Code , DBRef , Decimal128 , deserialize , Document , Double , Int32 , Long , MaxKey , MinKey , ObjectId , serialize , Timestamp , UUID } from 'bson';
import type { SrvRecord } from 'dns';
import { EventEmitter } from 'events';
import type { Socket , TcpNetConnectOpts } from 'net';
import { Readable , Writable } from 'stream';
import type { ConnectionOptions as ConnectionOptions_2 , TLSSocket , TLSSocketOptions } from 'tls';
/** @public */
export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> {
/* Excluded from this release type: [kId] */
/* Excluded from this release type: [kSession] */
/* Excluded from this release type: [kServer] */
/* Excluded from this release type: [kNamespace] */
/* Excluded from this release type: [kDocuments] */
/* Excluded from this release type: [kClient] */
/* Excluded from this release type: [kTransform] */
/* Excluded from this release type: [kInitialized] */
/* Excluded from this release type: [kClosed] */
/* Excluded from this release type: [kKilled] */
/* Excluded from this release type: [kOptions] */
/** @event */
static readonly CLOSE: "close";
/* Excluded from this release type: __constructor */
get id(): Long | undefined;
/* Excluded from this release type: isDead */
/* Excluded from this release type: client */
/* Excluded from this release type: server */
get namespace(): MongoDBNamespace;
get readPreference(): ReadPreference;
get readConcern(): ReadConcern | undefined;
/* Excluded from this release type: session */
/* Excluded from this release type: session */
/* Excluded from this release type: cursorOptions */
get closed(): boolean;
get killed(): boolean;
get loadBalanced(): boolean;
/** Returns current buffered documents length */
bufferedCount(): number;
/** Returns current buffered documents */
readBufferedDocuments(number?: number): TSchema[];
[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;
stream(options?: CursorStreamOptions): Readable & AsyncIterable<TSchema>;
hasNext(): Promise<boolean>;
/** Get the next available document from the cursor, returns null if no more documents are available. */
next(): Promise<TSchema | null>;
/**
* Try to get the next available document from the cursor or `null` if an empty batch is returned
*/
tryNext(): Promise<TSchema | null>;
/**
* Iterates over all the documents for this cursor using the iterator, callback pattern.
*
* If the iterator returns `false`, iteration will stop.
*
* @param iterator - The iteration callback.
* @deprecated - Will be removed in a future release. Use for await...of instead.
*/
forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;
close(): Promise<void>;
/**
* Returns an array of documents. The caller is responsible for making sure that there
* is enough memory to store the results. Note that the array only contains partial
* results when this cursor had been previously accessed. In that case,
* cursor.rewind() can be used to reset the cursor.
*/
toArray(): Promise<TSchema[]>;
/**
* Add a cursor flag to the cursor
*
* @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
* @param value - The flag boolean value.
*/
addCursorFlag(flag: CursorFlag, value: boolean): this;
/**
* Map all documents using the provided function
* If there is a transform set on the cursor, that will be called first and the result passed to
* this function's transform.
*
* @remarks
*
* **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
* function that maps values to `null` will result in the cursor closing itself before it has finished iterating
* all documents. This will **not** result in a memory leak, just surprising behavior. For example:
*
* ```typescript
* const cursor = collection.find({});
* cursor.map(() => null);
*
* const documents = await cursor.toArray();
* // documents is always [], regardless of how many documents are in the collection.
* ```
*
* Other falsey values are allowed:
*
* ```typescript
* const cursor = collection.find({});
* cursor.map(() => '');
*
* const documents = await cursor.toArray();
* // documents is now an array of empty strings
* ```
*
* **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
* it **does not** return a new instance of a cursor. This means when calling map,
* you should always assign the result to a new variable in order to get a correctly typed cursor variable.
* Take note of the following example:
*
* @example
* ```typescript
* const cursor: FindCursor<Document> = coll.find();
* const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
* const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
* ```
* @param transform - The mapping transformation method.
*/
map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T>;
/**
* Set the ReadPreference for the cursor.
*
* @param readPreference - The new read preference for the cursor.
*/
withReadPreference(readPreference: ReadPreferenceLike): this;
/**
* Set the ReadPreference for the cursor.
*
* @param readPreference - The new read preference for the cursor.
*/
withReadConcern(readConcern: ReadConcernLike): this;
/**
* Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
*
* @param value - Number of milliseconds to wait before aborting the query.
*/
maxTimeMS(value: number): this;
/**
* Set the batch size for the cursor.
*
* @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
*/
batchSize(value: number): this;
/**
* Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
* remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
* if the resultant data has already been retrieved by this cursor.
*/
rewind(): void;
/**
* Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
*/
abstract clone(): AbstractCursor<TSchema>;
/* Excluded from this release type: _initialize */
/* Excluded from this release type: getMore */
/* Excluded from this release type: [kInit] */
}
/** @public */
export declare type AbstractCursorEvents = {
[AbstractCursor.CLOSE](): void;
};
/** @public */
export declare interface AbstractCursorOptions extends BSONSerializeOptions {
session?: ClientSession;
readPreference?: ReadPreferenceLike;
readConcern?: ReadConcernLike;
/**
* Specifies the number of documents to return in each response from MongoDB
*/
batchSize?: number;
/**
* When applicable `maxTimeMS` controls the amount of time the initial command
* that constructs a cursor should take. (ex. find, aggregate, listCollections)
*/
maxTimeMS?: number;
/**
* When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores
* that a cursor uses to fetch more data should take. (ex. cursor.next())
*/
maxAwaitTimeMS?: number;
/**
* Comment to apply to the operation.
*
* In server versions pre-4.4, 'comment' must be string. A server
* error will be thrown if any other type is provided.
*
* In server versions 4.4 and above, 'comment' can be any valid BSON type.
*/
comment?: unknown;
/**
* By default, MongoDB will automatically close a cursor when the
* client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)
* you may use a Tailable Cursor that remains open after the client exhausts
* the results in the initial cursor.
*/
tailable?: boolean;
/**
* If awaitData is set to true, when the cursor reaches the end of the capped collection,
* MongoDB blocks the query thread for a period of time waiting for new data to arrive.
* When new data is inserted into the capped collection, the blocked thread is signaled
* to wake up and return the next batch to the client.
*/
awaitData?: boolean;
noCursorTimeout?: boolean;
}
/* Excluded from this release type: AbstractOperation */
/** @public */
export declare type AcceptedFields<TSchema, FieldType, AssignableType> = {
readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;
};
/** @public */
export declare type AddToSetOperators<Type> = {
$each?: Array<Flatten<Type>>;
};
/**
* The **Admin** class is an internal class that allows convenient access to
* the admin functionality and commands for MongoDB.
*
* **ADMIN Cannot directly be instantiated**
* @public
*
* @example
* ```ts
* import { MongoClient } from 'mongodb';
*
* const client = new MongoClient('mongodb://localhost:27017');
* const admin = client.db().admin();
* const dbInfo = await admin.listDatabases();
* for (const db of dbInfo.databases) {
* console.log(db.name);
* }
* ```
*/
export declare class Admin {
/* Excluded from this release type: s */
/* Excluded from this release type: __constructor */
/**
* Execute a command
*
* The driver will ensure the following fields are attached to the command sent to the server:
* - `lsid` - sourced from an implicit session or options.session
* - `$readPreference` - defaults to primary or can be configured by options.readPreference
* - `$db` - sourced from the name of this database
*
* If the client has a serverApi setting:
* - `apiVersion`
* - `apiStrict`
* - `apiDeprecationErrors`
*
* When in a transaction:
* - `readConcern` - sourced from readConcern set on the TransactionOptions
* - `writeConcern` - sourced from writeConcern set on the TransactionOptions
*
* Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
*
* @param command - The command to execute
* @param options - Optional settings for the command
*/
command(command: Document, options?: RunCommandOptions): Promise<Document>;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
*/
buildInfo(options?: CommandOperationOptions): Promise<Document>;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
*/
serverInfo(options?: CommandOperationOptions): Promise<Document>;
/**
* Retrieve this db's server status.
*
* @param options - Optional settings for the command
*/
serverStatus(options?: CommandOperationOptions): Promise<Document>;
/**
* Ping the MongoDB server and retrieve results
*
* @param options - Optional settings for the command
*/
ping(options?: CommandOperationOptions): Promise<Document>;
/**
* Remove a user from a database
*
* @param username - The username to remove
* @param options - Optional settings for the command
*/
removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
/**
* Validate an existing collection
*
* @param collectionName - The name of the collection to validate.
* @param options - Optional settings for the command
*/
validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise<Document>;
/**
* List the available databases
*
* @param options - Optional settings for the command
*/
listDatabases(options?: ListDatabasesOptions): Promise<ListDatabasesResult>;
/**
* Get ReplicaSet status
*
* @param options - Optional settings for the command
*/
replSetGetStatus(options?: CommandOperationOptions): Promise<Document>;
}
/* Excluded from this release type: AdminPrivate */
/* Excluded from this release type: AggregateOperation */
/** @public */
export declare interface AggregateOptions extends CommandOperationOptions {
/** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */
allowDiskUse?: boolean;
/** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */
batchSize?: number;
/** Allow driver to bypass schema validation. */
bypassDocumentValidation?: boolean;
/** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */
cursor?: Document;
/** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */
maxTimeMS?: number;
/** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */
maxAwaitTimeMS?: number;
/** Specify collation. */
collation?: CollationOptions;
/** Add an index selection hint to an aggregation command */
hint?: Hint;
/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
let?: Document;
out?: string;
}
/**
* The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
* allowing for iteration over the results returned from the underlying query. It supports
* one by one document iteration, conversion to an array or can be iterated as a Node 4.X
* or higher stream
* @public
*/
export declare class AggregationCursor<TSchema = any> extends AbstractCursor<TSchema> {
/* Excluded from this release type: [kPipeline] */
/* Excluded from this release type: [kOptions] */
/* Excluded from this release type: __constructor */
get pipeline(): Document[];
clone(): AggregationCursor<TSchema>;
map<T>(transform: (doc: TSchema) => T): AggregationCursor<T>;
/* Excluded from this release type: _initialize */
/** Execute the explain for the cursor */
explain(verbosity?: ExplainVerbosityLike): Promise<Document>;
/** Add a group stage to the aggregation pipeline */
group<T = TSchema>($group: Document): AggregationCursor<T>;
/** Add a limit stage to the aggregation pipeline */
limit($limit: number): this;
/** Add a match stage to the aggregation pipeline */
match($match: Document): this;
/** Add an out stage to the aggregation pipeline */
out($out: {
db: string;
coll: string;
} | string): this;
/**
* Add a project stage to the aggregation pipeline
*
* @remarks
* In order to strictly type this function you must provide an interface
* that represents the effect of your projection on the result documents.
*
* By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
* You should specify a parameterized type to have assertions on your final results.
*
* @example
* ```typescript
* // Best way
* const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
* // Flexible way
* const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
* ```
*
* @remarks
* In order to strictly type this function you must provide an interface
* that represents the effect of your projection on the result documents.
*
* **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
* it **does not** return a new instance of a cursor. This means when calling project,
* you should always assign the result to a new variable in order to get a correctly typed cursor variable.
* Take note of the following example:
*
* @example
* ```typescript
* const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
* const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
* const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
*
* // or always use chaining and save the final cursor
*
* const cursor = coll.aggregate().project<{ a: string }>({
* _id: 0,
* a: { $convert: { input: '$a', to: 'string' }
* }});
* ```
*/
project<T extends Document = Document>($project: Document): AggregationCursor<T>;
/** Add a lookup stage to the aggregation pipeline */
lookup($lookup: Document): this;
/** Add a redact stage to the aggregation pipeline */
redact($redact: Document): this;
/** Add a skip stage to the aggregation pipeline */
skip($skip: number): this;
/** Add a sort stage to the aggregation pipeline */
sort($sort: Sort): this;
/** Add a unwind stage to the aggregation pipeline */
unwind($unwind: Document | string): this;
/** Add a geoNear stage to the aggregation pipeline */
geoNear($geoNear: Document): this;
}
/** @public */
export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {
}
/**
* It is possible to search using alternative types in mongodb e.g.
* string types can be searched using a regex in mongo
* array types can be searched using their element type
* @public
*/
export declare type AlternativeType<T> = T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;
/** @public */
export declare type AnyBulkWriteOperation<TSchema extends Document = Document> = {
insertOne: InsertOneModel<TSchema>;
} | {
replaceOne: ReplaceOneModel<TSchema>;
} | {
updateOne: UpdateOneModel<TSchema>;
} | {
updateMany: UpdateManyModel<TSchema>;
} | {
deleteOne: DeleteOneModel<TSchema>;
} | {
deleteMany: DeleteManyModel<TSchema>;
};
/** @public */
export declare type AnyError = MongoError | Error;
/** @public */
export declare type ArrayElement<Type> = Type extends ReadonlyArray<infer Item> ? Item : never;
/** @public */
export declare type ArrayOperator<Type> = {
$each?: Array<Flatten<Type>>;
$slice?: number;
$position?: number;
$sort?: Sort;
};
/** @public */
export declare interface Auth {
/** The username for auth */
username?: string;
/** The password for auth */
password?: string;
}
/* Excluded from this release type: AuthContext */
/** @public */
export declare const AuthMechanism: Readonly<{
readonly MONGODB_AWS: "MONGODB-AWS";
readonly MONGODB_CR: "MONGODB-CR";
readonly MONGODB_DEFAULT: "DEFAULT";
readonly MONGODB_GSSAPI: "GSSAPI";
readonly MONGODB_PLAIN: "PLAIN";
readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";
readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";
readonly MONGODB_X509: "MONGODB-X509";
/** @experimental */
readonly MONGODB_OIDC: "MONGODB-OIDC";
}>;
/** @public */
export declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];
/** @public */
export declare interface AuthMechanismProperties extends Document {
SERVICE_HOST?: string;
SERVICE_NAME?: string;
SERVICE_REALM?: string;
CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;
AWS_SESSION_TOKEN?: string;
/** @experimental */
REQUEST_TOKEN_CALLBACK?: OIDCRequestFunction;
/** @experimental */
REFRESH_TOKEN_CALLBACK?: OIDCRefreshFunction;
/** @experimental */
PROVIDER_NAME?: 'aws' | 'azure';
/** @experimental */
ALLOWED_HOSTS?: string[];
/** @experimental */
TOKEN_AUDIENCE?: string;
}
/* Excluded from this release type: AutoEncrypter */
/**
* @public
*
* Extra options related to the mongocryptd process
* \* _Available in MongoDB 6.0 or higher._
*/
export declare type AutoEncryptionExtraOptions = NonNullable<AutoEncryptionOptions['extraOptions']>;
/** @public */
export declare const AutoEncryptionLoggerLevel: Readonly<{
readonly FatalError: 0;
readonly Error: 1;
readonly Warning: 2;
readonly Info: 3;
readonly Trace: 4;
}>;
/**
* @public
* The level of severity of the log message
*
* | Value | Level |
* |-------|-------|
* | 0 | Fatal Error |
* | 1 | Error |
* | 2 | Warning |
* | 3 | Info |
* | 4 | Trace |
*/
export declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];
/** @public */
export declare interface AutoEncryptionOptions {
/* Excluded from this release type: metadataClient */
/** A `MongoClient` used to fetch keys from a key vault */
keyVaultClient?: MongoClient;
/** The namespace where keys are stored in the key vault */
keyVaultNamespace?: string;
/** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */
kmsProviders?: {
/** Configuration options for using 'aws' as your KMS provider */
aws?: {
/** The access key used for the AWS KMS provider */
accessKeyId: string;
/** The secret access key used for the AWS KMS provider */
secretAccessKey: string;
/**
* An optional AWS session token that will be used as the
* X-Amz-Security-Token header for AWS requests.
*/
sessionToken?: string;
} | Record<string, never>;
/** Configuration options for using 'local' as your KMS provider */
local?: {
/**
* The master key used to encrypt/decrypt data keys.
* A 96-byte long Buffer or base64 encoded string.
*/
key: Buffer | string;
};
/** Configuration options for using 'azure' as your KMS provider */
azure?: {
/** The tenant ID identifies the organization for the account */
tenantId: string;
/** The client ID to authenticate a registered application */
clientId: string;
/** The client secret to authenticate a registered application */
clientSecret: string;
/**
* If present, a host with optional port. E.g. "example.com" or "example.com:443".
* This is optional, and only needed if customer is using a non-commercial Azure instance
* (e.g. a government or China account, which use different URLs).
* Defaults to "login.microsoftonline.com"
*/
identityPlatformEndpoint?: string | undefined;
} | {
/**
* If present, an access token to authenticate with Azure.
*/
accessToken: string;
} | Record<string, never>;
/** Configuration options for using 'gcp' as your KMS provider */
gcp?: {
/** The service account email to authenticate */
email: string;
/** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */
privateKey: string | Buffer;
/**
* If present, a host with optional port. E.g. "example.com" or "example.com:443".
* Defaults to "oauth2.googleapis.com"
*/
endpoint?: string | undefined;
} | {
/**
* If present, an access token to authenticate with GCP.
*/
accessToken: string;
} | Record<string, never>;
/**
* Configuration options for using 'kmip' as your KMS provider
*/
kmip?: {
/**
* The output endpoint string.
* The endpoint consists of a hostname and port separated by a colon.
* E.g. "example.com:123". A port is always present.
*/
endpoint?: string;
};
};
/**
* A map of namespaces to a local JSON schema for encryption
*
* **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
* It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
* Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
* Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
*/
schemaMap?: Document;
/** Supply a schema for the encrypted fields in the document */
encryptedFieldsMap?: Document;
/** Allows the user to bypass auto encryption, maintaining implicit decryption */
bypassAutoEncryption?: boolean;
/** Allows users to bypass query analysis */
bypassQueryAnalysis?: boolean;
options?: {
/** An optional hook to catch logging messages from the underlying encryption engine */
logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
};
extraOptions?: {
/**
* A local process the driver communicates with to determine how to encrypt values in a command.
* Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
*/
mongocryptdURI?: string;
/** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */
mongocryptdBypassSpawn?: boolean;
/** The path to the mongocryptd executable on the system */
mongocryptdSpawnPath?: string;
/** Command line arguments to use when auto-spawning a mongocryptd */
mongocryptdSpawnArgs?: string[];
/**
* Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd).
*
* This needs to be the path to the file itself, not a directory.
* It can be an absolute or relative path. If the path is relative and
* its first component is `$ORIGIN`, it will be replaced by the directory
* containing the mongodb-client-encryption native addon file. Otherwise,
* the path will be interpreted relative to the current working directory.
*
* Currently, loading different MongoDB Crypt shared library files from different
* MongoClients in the same process is not supported.
*
* If this option is provided and no MongoDB Crypt shared library could be loaded
* from the specified location, creating the MongoClient will fail.
*
* If this option is not provided and `cryptSharedLibRequired` is not specified,
* the AutoEncrypter will attempt to spawn and/or use mongocryptd according
* to the mongocryptd-specific `extraOptions` options.
*
* Specifying a path prevents mongocryptd from being used as a fallback.
*
* Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
*/
cryptSharedLibPath?: string;
/**
* If specified, never use mongocryptd and instead fail when the MongoDB Crypt
* shared library could not be loaded.
*
* This is always true when `cryptSharedLibPath` is specified.
*
* Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
*/
cryptSharedLibRequired?: boolean;
/* Excluded from this release type: cryptSharedLibSearchPaths */
};
proxyOptions?: ProxyOptions;
/** The TLS options to use connecting to the KMS provider */
tlsOptions?: CSFLEKMSTlsOptions;
}
/**
* @public
* Configuration options for making an AWS encryption key
*/
export declare interface AWSEncryptionKeyOptions {
/**
* The AWS region of the KMS
*/
region: string;
/**
* The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
*/
key: string;
/**
* An alternate host to send KMS requests to. May include port number.
*/
endpoint?: string | undefined;
}
/**
* @public
* Configuration options for making an Azure encryption key
*/
export declare interface AzureEncryptionKeyOptions {
/**
* Key name
*/
keyName: string;
/**
* Key vault URL, typically `<name>.vault.azure.net`
*/
keyVaultEndpoint: string;
/**
* Key version
*/
keyVersion?: string | undefined;
}
/**
* Keeps the state of a unordered batch so we can rewrite the results
* correctly after command execution
*
* @public
*/
export declare class Batch<T = Document> {
originalZeroIndex: number;
currentIndex: number;
originalIndexes: number[];
batchType: BatchType;
operations: T[];
size: number;
sizeBytes: number;
constructor(batchType: BatchType, originalZeroIndex: number);
}
/** @public */
export declare const BatchType: Readonly<{
readonly INSERT: 1;
readonly UPDATE: 2;
readonly DELETE: 3;
}>;
/** @public */
export declare type BatchType = (typeof BatchType)[keyof typeof BatchType];
export { Binary }
/** @public */
export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray<number>;
export { BSON }
export { BSONRegExp }
/**
* BSON Serialization options.
* @public
*/
export declare interface BSONSerializeOptions extends Omit<SerializeOptions, 'index'>, Omit<DeserializeOptions, 'evalFunctions' | 'cacheFunctions' | 'cacheFunctionsCrc32' | 'allowObjectSmallerThanBufferSize' | 'index' | 'validation'> {
/**
* Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html)
* which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize).
* See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe)
* for more detail about what "unsafe" refers to in this context.
* If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate
* your own buffer and clone the contents:
*
* @example
* ```ts
* const raw = await collection.findOne({}, { raw: true });
* const myBuffer = Buffer.alloc(raw.byteLength);
* myBuffer.set(raw, 0);
* // Only save and use `myBuffer` beyond this point
* ```
*
* @remarks
* Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)).
* It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work.
*/
raw?: boolean;
/** Enable utf8 validation when deserializing BSON documents. Defaults to true. */
enableUtf8Validation?: boolean;
}
export { BSONSymbol }
export { BSONType }
/** @public */
export declare type BSONTypeAlias = keyof typeof BSONType;
/* Excluded from this release type: BufferPool */
/** @public */
export declare abstract class BulkOperationBase {
isOrdered: boolean;
/* Excluded from this release type: s */
operationId?: number;
/* Excluded from this release type: __constructor */
/**
* Add a single insert document to the bulk operation
*
* @example
* ```ts
* const bulkOp = collection.initializeOrderedBulkOp();
*
* // Adds three inserts to the bulkOp.
* bulkOp
* .insert({ a: 1 })
* .insert({ b: 2 })
* .insert({ c: 3 });
* await bulkOp.execute();
* ```
*/
insert(document: Document): BulkOperationBase;
/**
* Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
* Returns a builder object used to complete the definition of the operation.
*
* @example
* ```ts
* const bulkOp = collection.initializeOrderedBulkOp();
*
* // Add an updateOne to the bulkOp
* bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
*
* // Add an updateMany to the bulkOp
* bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
*
* // Add an upsert
* bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
*
* // Add a deletion
* bulkOp.find({ g: 7 }).deleteOne();
*
* // Add a multi deletion
* bulkOp.find({ h: 8 }).delete();
*
* // Add a replaceOne
* bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
*
* // Update using a pipeline (requires Mongodb 4.2 or higher)
* bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
* { $set: { total: { $sum: [ '$y', '$z' ] } } }
* ]);
*
* // All of the ops will now be executed
* await bulkOp.execute();
* ```
*/
find(selector: Document): FindOperators;
/** Specifies a raw operation to perform in the bulk write. */
raw(op: AnyBulkWriteOperation): this;
get bsonOptions(): BSONSerializeOptions;
get writeConcern(): WriteConcern | undefined;
get batches(): Batch[];
execute(options?: BulkWriteOptions): Promise<BulkWriteResult>;
/* Excluded from this release type: handleWriteError */
abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
}
/* Excluded from this release type: BulkOperationPrivate */
/* Excluded from this release type: BulkResult */
/** @public */
export declare interface BulkWriteOperationError {
index: number;
code: number;
errmsg: string;
errInfo: Document;
op: Document | UpdateStatement | DeleteStatement;
}
/** @public */
export declare interface BulkWriteOptions extends CommandOperationOptions {
/**
* Allow driver to bypass schema validation.
* @defaultValue `false` - documents will be validated by default
**/
bypassDocumentValidation?: boolean;
/**
* If true, when an insert fails, don't execute the remaining writes.
* If false, continue with remaining inserts when one fails.
* @defaultValue `true` - inserts are ordered by default
*/
ordered?: boolean;
/**
* Force server to assign _id values instead of driver.
* @defaultValue `false` - the driver generates `_id` fields by default
**/
forceServerObjectId?: boolean;
/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
let?: Document;
}
/**
* @public
* The result of a bulk write.
*/
export declare class BulkWriteResult {
private readonly result;
/** Number of documents inserted. */
readonly insertedCount: number;
/** Number of documents matched for update. */
readonly matchedCount: number;
/** Number of documents modified. */
readonly modifiedCount: number;
/** Number of documents deleted. */
readonly deletedCount: number;
/** Number of documents upserted. */
readonly upsertedCount: number;
/** Upserted document generated Id's, hash key is the index of the originating operation */
readonly upsertedIds: {
[key: number]: any;
};
/** Inserted document generated Id's, hash key is the index of the originating operation */
readonly insertedIds: {
[key: number]: any;
};
private static generateIdMap;
/* Excluded from this release type: __constructor */
/** Evaluates to true if the bulk operation correctly executes */
get ok(): number;
/* Excluded from this release type: getSuccessfullyInsertedIds */
/** Returns the upserted id at the given index */
getUpsertedIdAt(index: number): Document | undefined;
/** Returns raw internal result */
getRawResponse(): Document;
/** Returns true if the bulk operation contains a write error */
hasWriteErrors(): boolean;
/** Returns the number of write errors off the bulk operation */
getWriteErrorCount(): number;
/** Returns a specific write error object */
getWriteErrorAt(index: number): WriteError | undefined;
/** Retrieve all write errors */
getWriteErrors(): WriteError[];
/** Retrieve the write concern error if one exists */
getWriteConcernError(): WriteConcernError | undefined;
toString(): string;
isOk(): boolean;
}
/**
* MongoDB Driver style callback
* @public
*/
export declare type Callback<T = any> = (error?: AnyError, result?: T) => void;
/** @public */
export declare class CancellationToken extends TypedEventEmitter<{
cancel(): void;
}> {
}
/**
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
* @public
*/
export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> {
pipeline: Document[];
/**
* @remarks WriteConcern can still be present on the options because
* we inherit options from the client/db/collection. The
* key must be present on the options in order to delete it.
* This allows typescript to delete the key but will
* not allow a writeConcern to be assigned as a property on options.
*/
options: ChangeStreamOptions & {
writeConcern?: never;
};
parent: MongoClient | Db | Collection;
namespace: MongoDBNamespace;
type: symbol;
/* Excluded from this release type: cursor */
streamOptions?: CursorStreamOptions;
/* Excluded from this release type: [kCursorStream] */
/* Excluded from this release type: [kClosed] */
/* Excluded from this release type: [kMode] */
/** @event */
static readonly RESPONSE: "response";
/** @event */