mongodb 6.16.0 → 6.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +2 -0
  2. package/lib/beta.d.ts +132 -33
  3. package/lib/bulk/common.js +4 -4
  4. package/lib/bulk/common.js.map +1 -1
  5. package/lib/client-side-encryption/auto_encrypter.js +5 -2
  6. package/lib/client-side-encryption/auto_encrypter.js.map +1 -1
  7. package/lib/client-side-encryption/client_encryption.js.map +1 -1
  8. package/lib/client-side-encryption/state_machine.js +1 -1
  9. package/lib/client-side-encryption/state_machine.js.map +1 -1
  10. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js +6 -0
  11. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -1
  12. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js +21 -33
  13. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -1
  14. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js +14 -21
  15. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -1
  16. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js +19 -26
  17. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js.map +1 -1
  18. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js +12 -24
  19. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -1
  20. package/lib/cmap/auth/mongodb_oidc.js +5 -4
  21. package/lib/cmap/auth/mongodb_oidc.js.map +1 -1
  22. package/lib/cmap/connect.js +4 -3
  23. package/lib/cmap/connect.js.map +1 -1
  24. package/lib/cmap/connection.js +8 -3
  25. package/lib/cmap/connection.js.map +1 -1
  26. package/lib/cmap/connection_pool.js +6 -1
  27. package/lib/cmap/connection_pool.js.map +1 -1
  28. package/lib/cmap/wire_protocol/constants.js +2 -2
  29. package/lib/cmap/wire_protocol/responses.js.map +1 -1
  30. package/lib/collection.js.map +1 -1
  31. package/lib/connection_string.js +2 -0
  32. package/lib/connection_string.js.map +1 -1
  33. package/lib/constants.js +0 -1
  34. package/lib/constants.js.map +1 -1
  35. package/lib/encrypter.js +3 -7
  36. package/lib/encrypter.js.map +1 -1
  37. package/lib/error.js +28 -1
  38. package/lib/error.js.map +1 -1
  39. package/lib/index.js +4 -3
  40. package/lib/index.js.map +1 -1
  41. package/lib/mongo_client.js +66 -20
  42. package/lib/mongo_client.js.map +1 -1
  43. package/lib/operations/aggregate.js +0 -1
  44. package/lib/operations/aggregate.js.map +1 -1
  45. package/lib/operations/client_bulk_write/command_builder.js +20 -13
  46. package/lib/operations/client_bulk_write/command_builder.js.map +1 -1
  47. package/lib/operations/find_and_modify.js +1 -1
  48. package/lib/operations/find_and_modify.js.map +1 -1
  49. package/lib/operations/update.js +6 -2
  50. package/lib/operations/update.js.map +1 -1
  51. package/lib/sdam/server.js +4 -1
  52. package/lib/sdam/server.js.map +1 -1
  53. package/lib/sdam/topology.js +9 -4
  54. package/lib/sdam/topology.js.map +1 -1
  55. package/lib/sort.js +13 -6
  56. package/lib/sort.js.map +1 -1
  57. package/lib/utils.js +15 -1
  58. package/lib/utils.js.map +1 -1
  59. package/mongodb.d.ts +132 -33
  60. package/package.json +19 -19
  61. package/src/bulk/common.ts +11 -6
  62. package/src/client-side-encryption/auto_encrypter.ts +10 -2
  63. package/src/client-side-encryption/client_encryption.ts +5 -0
  64. package/src/client-side-encryption/state_machine.ts +1 -1
  65. package/src/cmap/auth/mongodb_oidc/automated_callback_workflow.ts +6 -0
  66. package/src/cmap/auth/mongodb_oidc/azure_machine_workflow.ts +23 -35
  67. package/src/cmap/auth/mongodb_oidc/gcp_machine_workflow.ts +16 -23
  68. package/src/cmap/auth/mongodb_oidc/k8s_machine_workflow.ts +17 -25
  69. package/src/cmap/auth/mongodb_oidc/token_machine_workflow.ts +11 -24
  70. package/src/cmap/auth/mongodb_oidc.ts +13 -8
  71. package/src/cmap/connect.ts +4 -3
  72. package/src/cmap/connection.ts +11 -4
  73. package/src/cmap/connection_pool.ts +8 -1
  74. package/src/cmap/wire_protocol/constants.ts +2 -2
  75. package/src/cmap/wire_protocol/on_demand/document.ts +1 -1
  76. package/src/cmap/wire_protocol/responses.ts +2 -2
  77. package/src/collection.ts +2 -1
  78. package/src/connection_string.ts +2 -0
  79. package/src/constants.ts +0 -1
  80. package/src/encrypter.ts +3 -10
  81. package/src/error.ts +28 -0
  82. package/src/index.ts +1 -0
  83. package/src/mongo_client.ts +73 -21
  84. package/src/operations/aggregate.ts +0 -1
  85. package/src/operations/client_bulk_write/command_builder.ts +32 -14
  86. package/src/operations/client_bulk_write/common.ts +5 -0
  87. package/src/operations/find_and_modify.ts +1 -1
  88. package/src/operations/update.ts +12 -3
  89. package/src/sdam/server.ts +5 -1
  90. package/src/sdam/topology.ts +10 -4
  91. package/src/sort.ts +32 -23
  92. package/src/utils.ts +21 -1
  93. package/lib/cmap/auth/mongodb_oidc/machine_workflow.js +0 -110
  94. package/lib/cmap/auth/mongodb_oidc/machine_workflow.js.map +0 -1
  95. package/src/cmap/auth/mongodb_oidc/machine_workflow.ts +0 -142
package/mongodb.d.ts CHANGED
@@ -770,6 +770,10 @@ export declare interface AutoEncryptionOptions {
770
770
  bypassAutoEncryption?: boolean;
771
771
  /** Allows users to bypass query analysis */
772
772
  bypassQueryAnalysis?: boolean;
773
+ /**
774
+ * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
775
+ */
776
+ keyExpirationMS?: number;
773
777
  options?: {
774
778
  /** An optional hook to catch logging messages from the underlying encryption engine */
775
779
  logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
@@ -1142,7 +1146,7 @@ export declare class BulkWriteResult {
1142
1146
  getRawResponse(): Document;
1143
1147
  /** Returns true if the bulk operation contains a write error */
1144
1148
  hasWriteErrors(): boolean;
1145
- /** Returns the number of write errors off the bulk operation */
1149
+ /** Returns the number of write errors from the bulk operation */
1146
1150
  getWriteErrorCount(): number;
1147
1151
  /** Returns a specific write error object */
1148
1152
  getWriteErrorAt(index: number): WriteError | undefined;
@@ -2164,6 +2168,10 @@ export declare interface ClientEncryptionOptions {
2164
2168
  * TLS options for kms providers to use.
2165
2169
  */
2166
2170
  tlsOptions?: CSFLEKMSTlsOptions;
2171
+ /**
2172
+ * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
2173
+ */
2174
+ keyExpirationMS?: number;
2167
2175
  /**
2168
2176
  * @experimental
2169
2177
  *
@@ -2307,6 +2315,8 @@ export declare interface ClientReplaceOneModel<TSchema> extends ClientWriteModel
2307
2315
  hint?: Hint;
2308
2316
  /** When true, creates a new document if no document matches the query. */
2309
2317
  upsert?: boolean;
2318
+ /** Specifies the sort order for the documents matched by the filter. */
2319
+ sort?: Sort;
2310
2320
  }
2311
2321
 
2312
2322
  /**
@@ -2539,6 +2549,8 @@ export declare interface ClientUpdateOneModel<TSchema> extends ClientWriteModel
2539
2549
  hint?: Hint;
2540
2550
  /** When true, creates a new document if no document matches the query. */
2541
2551
  upsert?: boolean;
2552
+ /** Specifies the sort order for the documents matched by the filter. */
2553
+ sort?: Sort;
2542
2554
  }
2543
2555
 
2544
2556
  /** @public */
@@ -2739,7 +2751,9 @@ export declare class Collection<TSchema extends Document = Document> {
2739
2751
  * @param update - The modifications to apply
2740
2752
  * @param options - Optional settings for the command
2741
2753
  */
2742
- updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
2754
+ updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions & {
2755
+ sort?: Sort;
2756
+ }): Promise<UpdateResult<TSchema>>;
2743
2757
  /**
2744
2758
  * Replace a document in a collection with another document
2745
2759
  *
@@ -5364,7 +5378,7 @@ export declare interface KMSProviders {
5364
5378
  /* Excluded from this release type: LegacyTimeoutContextOptions */
5365
5379
 
5366
5380
  /** @public */
5367
- export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["autoSelectFamily", "autoSelectFamilyAttemptTimeout", "family", "hints", "localAddress", "localPort", "lookup"];
5381
+ export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["autoSelectFamily", "autoSelectFamilyAttemptTimeout", "keepAliveInitialDelay", "family", "hints", "localAddress", "localPort", "lookup"];
5368
5382
 
5369
5383
  /** @public */
5370
5384
  export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["allowPartialTrustChain", "ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"];
@@ -5674,22 +5688,35 @@ export declare class MongoChangeStreamError extends MongoRuntimeError {
5674
5688
  }
5675
5689
 
5676
5690
  /**
5677
- * The **MongoClient** class is a class that allows for making Connections to MongoDB.
5678
5691
  * @public
5679
5692
  *
5693
+ * The **MongoClient** class is a class that allows for making Connections to MongoDB.
5694
+ *
5695
+ * **NOTE:** The programmatically provided options take precedence over the URI options.
5696
+ *
5680
5697
  * @remarks
5681
- * The programmatically provided options take precedence over the URI options.
5698
+ *
5699
+ * A MongoClient is the entry point to connecting to a MongoDB server.
5700
+ *
5701
+ * It handles a multitude of features on your application's behalf:
5702
+ * - **Server Host Connection Configuration**: A MongoClient is responsible for reading TLS cert, ca, and crl files if provided.
5703
+ * - **SRV Record Polling**: A "`mongodb+srv`" style connection string is used to have the MongoClient resolve DNS SRV records of all server hostnames which the driver periodically monitors for changes and adjusts its current view of hosts correspondingly.
5704
+ * - **Server Monitoring**: The MongoClient automatically keeps monitoring the health of server nodes in your cluster to reach out to the correct and lowest latency one available.
5705
+ * - **Connection Pooling**: To avoid paying the cost of rebuilding a connection to the server on every operation the MongoClient keeps idle connections preserved for reuse.
5706
+ * - **Session Pooling**: The MongoClient creates logical sessions that enable retryable writes, causal consistency, and transactions. It handles pooling these sessions for reuse in subsequent operations.
5707
+ * - **Cursor Operations**: A MongoClient's cursors use the health monitoring system to send the request for more documents to the same server the query began on.
5708
+ * - **Mongocryptd process**: When using auto encryption, a MongoClient will launch a `mongocryptd` instance for handling encryption if the mongocrypt shared library isn't in use.
5709
+ *
5710
+ * There are many more features of a MongoClient that are not listed above.
5711
+ *
5712
+ * In order to enable these features, a number of asynchronous Node.js resources are established by the driver: Timers, FS Requests, Sockets, etc.
5713
+ * For details on cleanup, please refer to the MongoClient `close()` documentation.
5682
5714
  *
5683
5715
  * @example
5684
5716
  * ```ts
5685
5717
  * import { MongoClient } from 'mongodb';
5686
- *
5687
5718
  * // Enable command monitoring for debugging
5688
- * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
5689
- *
5690
- * client.on('commandStarted', started => console.log(started));
5691
- * client.db().collection('pets');
5692
- * await client.insertOne({ name: 'spot', kind: 'dog' });
5719
+ * const client = new MongoClient('mongodb://localhost:27017?appName=mflix', { monitorCommands: true });
5693
5720
  * ```
5694
5721
  */
5695
5722
  export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable_2 {
@@ -5741,19 +5768,51 @@ export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> im
5741
5768
  connect(): Promise<this>;
5742
5769
  /* Excluded from this release type: _connect */
5743
5770
  /**
5744
- * Cleans up client-side resources used by the MongoCLient and . This includes:
5745
- *
5746
- * - Closes all open, unused connections (see note).
5747
- * - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
5748
- * - Ends all unused sessions server-side.
5749
- * - Cleans up any resources being used for auto encryption if auto encryption is enabled.
5750
- *
5751
- * @remarks Any in-progress operations are not killed and any connections used by in progress operations
5752
- * will be cleaned up lazily as operations finish.
5753
- *
5754
- * @param force - Force close, emitting no events
5755
- */
5756
- close(force?: boolean): Promise<void>;
5771
+ * Cleans up resources managed by the MongoClient.
5772
+ *
5773
+ * The close method clears and closes all resources whose lifetimes are managed by the MongoClient.
5774
+ * Please refer to the `MongoClient` class documentation for a high level overview of the client's key features and responsibilities.
5775
+ *
5776
+ * **However,** the close method does not handle the cleanup of resources explicitly created by the user.
5777
+ * Any user-created driver resource with its own `close()` method should be explicitly closed by the user before calling MongoClient.close().
5778
+ * This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible.
5779
+ *
5780
+ * The following list defines ideal preconditions and consequent pitfalls if they are not met.
5781
+ * The MongoClient, ClientSession, Cursors and ChangeStreams all support [explicit resource management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html).
5782
+ * By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided.
5783
+ *
5784
+ * The close method performs the following in the order listed:
5785
+ * - Client-side:
5786
+ * - **Close in-use connections**: Any connections that are currently waiting on a response from the server will be closed.
5787
+ * This is performed _first_ to avoid reaching the next step (server-side clean up) and having no available connections to check out.
5788
+ * - _Ideal_: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation.
5789
+ * - _Pitfall_: When `client.close()` is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps.
5790
+ * - Server-side:
5791
+ * - **Close active cursors**: All cursors that haven't been completed will have a `killCursor` operation sent to the server they were initialized on, freeing the server-side resource.
5792
+ * - _Ideal_: Cursors are explicitly closed or completed before `client.close()` is called.
5793
+ * - _Pitfall_: `killCursors` may have to build a new connection if the in-use closure ended all pooled connections.
5794
+ * - **End active sessions**: In-use sessions created with `client.startSession()` or `client.withSession()` or implicitly by the driver will have their `.endSession()` method called.
5795
+ * Contrary to the name of the method, `endSession()` returns the session to the client's pool of sessions rather than end them on the server.
5796
+ * - _Ideal_: Transaction outcomes are awaited and their corresponding explicit sessions are ended before `client.close()` is called.
5797
+ * - _Pitfall_: **This step aborts in-progress transactions**. It is advisable to observe the outcome of a transaction before closing your client.
5798
+ * - **End all pooled sessions**: The `endSessions` command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.
5799
+ * - _Ideal_: No user intervention is expected.
5800
+ * - _Pitfall_: None.
5801
+ *
5802
+ * The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop.
5803
+ *
5804
+ * - Client-side (again):
5805
+ * - **Stop all server monitoring**: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown.
5806
+ * - **Close all pooled connections**: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned.
5807
+ * - **Clear out server selection queue**: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned.
5808
+ * - **Close encryption-related resources**: An internal MongoClient created for communicating with `mongocryptd` or other encryption purposes is closed. (Using this same method of course!)
5809
+ *
5810
+ * After the close method completes there should be no MongoClient related resources [ref-ed in Node.js' event loop](https://docs.libuv.org/en/v1.x/handle.html#reference-counting).
5811
+ * This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop.
5812
+ *
5813
+ * @param _force - currently an unused flag that has no effect. Defaults to `false`.
5814
+ */
5815
+ close(_force?: boolean): Promise<void>;
5757
5816
  private _close;
5758
5817
  /**
5759
5818
  * Create a new Db instance sharing the current socket connections.
@@ -5946,6 +6005,29 @@ export declare class MongoClientBulkWriteExecutionError extends MongoRuntimeErro
5946
6005
  get name(): string;
5947
6006
  }
5948
6007
 
6008
+ /**
6009
+ * An error generated when the MongoClient is closed and async
6010
+ * operations are interrupted.
6011
+ *
6012
+ * @public
6013
+ * @category Error
6014
+ */
6015
+ export declare class MongoClientClosedError extends MongoAPIError {
6016
+ /**
6017
+ * **Do not use this constructor!**
6018
+ *
6019
+ * Meant for internal use only.
6020
+ *
6021
+ * @remarks
6022
+ * This class is only meant to be constructed within the driver. This constructor is
6023
+ * not subject to semantic versioning compatibility guarantees and may change at any time.
6024
+ *
6025
+ * @public
6026
+ **/
6027
+ constructor();
6028
+ get name(): string;
6029
+ }
6030
+
5949
6031
  /** @public */
5950
6032
  export declare type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS)[number]> & {
5951
6033
  open(mongoClient: MongoClient): void;
@@ -7345,6 +7427,8 @@ export declare interface OIDCCallbackParams {
7345
7427
  idpInfo?: IdPInfo;
7346
7428
  /** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
7347
7429
  refreshToken?: string;
7430
+ /** The token audience for GCP and Azure. */
7431
+ tokenAudience?: string;
7348
7432
  }
7349
7433
 
7350
7434
  /**
@@ -7678,7 +7762,7 @@ export declare interface RenameOptions extends CommandOperationOptions {
7678
7762
 
7679
7763
  /** @public */
7680
7764
  export declare interface ReplaceOneModel<TSchema extends Document = Document> {
7681
- /** The filter to limit the replaced document. */
7765
+ /** The filter that specifies which document to replace. In the case of multiple matches, the first document matched is replaced. */
7682
7766
  filter: Filter<TSchema>;
7683
7767
  /** The document with which to replace the matched document. */
7684
7768
  replacement: WithoutId<TSchema>;
@@ -7688,6 +7772,8 @@ export declare interface ReplaceOneModel<TSchema extends Document = Document> {
7688
7772
  hint?: Hint;
7689
7773
  /** When true, creates a new document if no document matches the query. */
7690
7774
  upsert?: boolean;
7775
+ /** Specifies the sort order for the documents matched by the filter. */
7776
+ sort?: Sort;
7691
7777
  }
7692
7778
 
7693
7779
  /** @public */
@@ -7702,6 +7788,8 @@ export declare interface ReplaceOptions extends CommandOperationOptions {
7702
7788
  upsert?: boolean;
7703
7789
  /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
7704
7790
  let?: Document;
7791
+ /** Specifies the sort order for the documents matched by the filter. */
7792
+ sort?: Sort;
7705
7793
  }
7706
7794
 
7707
7795
  /**
@@ -8214,19 +8302,24 @@ export declare type SeverityLevel = (typeof SeverityLevel)[keyof typeof Severity
8214
8302
 
8215
8303
  /** @public */
8216
8304
  export declare type Sort = string | Exclude<SortDirection, {
8217
- $meta: string;
8218
- }> | string[] | {
8219
- [key: string]: SortDirection;
8220
- } | Map<string, SortDirection> | [string, SortDirection][] | [string, SortDirection];
8305
+ readonly $meta: string;
8306
+ }> | ReadonlyArray<string> | {
8307
+ readonly [key: string]: SortDirection;
8308
+ } | ReadonlyMap<string, SortDirection> | ReadonlyArray<readonly [string, SortDirection]> | readonly [string, SortDirection];
8221
8309
 
8222
8310
  /** @public */
8223
8311
  export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | {
8224
- $meta: string;
8312
+ readonly $meta: string;
8225
8313
  };
8226
8314
 
8227
- /* Excluded from this release type: SortDirectionForCmd */
8315
+ /** Below stricter types were created for sort that correspond with type that the cmd takes */
8316
+ /** @public */
8317
+ export declare type SortDirectionForCmd = 1 | -1 | {
8318
+ $meta: string;
8319
+ };
8228
8320
 
8229
- /* Excluded from this release type: SortForCmd */
8321
+ /** @public */
8322
+ export declare type SortForCmd = Map<string, SortDirectionForCmd>;
8230
8323
 
8231
8324
  /* Excluded from this release type: SrvPoller */
8232
8325
 
@@ -8327,6 +8420,8 @@ export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptio
8327
8420
  export declare type SupportedSocketOptions = Pick<TcpNetConnectOpts & {
8328
8421
  autoSelectFamily?: boolean;
8329
8422
  autoSelectFamilyAttemptTimeout?: number;
8423
+ /** Node.JS socket option to set the time the first keepalive probe is sent on an idle socket. Defaults to 120000ms */
8424
+ keepAliveInitialDelay?: number;
8330
8425
  }, (typeof LEGAL_TCP_SOCKET_OPTIONS)[number]>;
8331
8426
 
8332
8427
  /** @public */
@@ -8694,7 +8789,7 @@ export declare interface UpdateManyModel<TSchema extends Document = Document> {
8694
8789
 
8695
8790
  /** @public */
8696
8791
  export declare interface UpdateOneModel<TSchema extends Document = Document> {
8697
- /** The filter to limit the updated documents. */
8792
+ /** The filter that specifies which document to update. In the case of multiple matches, the first document matched is updated. */
8698
8793
  filter: Filter<TSchema>;
8699
8794
  /**
8700
8795
  * The modifications to apply. The value can be either:
@@ -8710,6 +8805,8 @@ export declare interface UpdateOneModel<TSchema extends Document = Document> {
8710
8805
  hint?: Hint;
8711
8806
  /** When true, creates a new document if no document matches the query. */
8712
8807
  upsert?: boolean;
8808
+ /** Specifies the sort order for the documents matched by the filter. */
8809
+ sort?: Sort;
8713
8810
  }
8714
8811
 
8715
8812
  /** @public */
@@ -8761,6 +8858,8 @@ export declare interface UpdateStatement {
8761
8858
  arrayFilters?: Document[];
8762
8859
  /** A document or string that specifies the index to use to support the query predicate. */
8763
8860
  hint?: Hint;
8861
+ /** Specifies the sort order for the documents matched by the filter. */
8862
+ sort?: SortForCmd;
8764
8863
  }
8765
8864
 
8766
8865
  export { UUID }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongodb",
3
- "version": "6.16.0",
3
+ "version": "6.17.0",
4
4
  "description": "The official MongoDB driver for Node.js",
5
5
  "main": "lib/index.js",
6
6
  "files": [
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@mongodb-js/saslprep": "^1.1.9",
29
- "bson": "^6.10.3",
29
+ "bson": "^6.10.4",
30
30
  "mongodb-connection-string-url": "^3.0.0"
31
31
  },
32
32
  "peerDependencies": {
@@ -65,43 +65,43 @@
65
65
  "@aws-sdk/credential-providers": "^3.632.0",
66
66
  "@iarna/toml": "^2.2.5",
67
67
  "@istanbuljs/nyc-config-typescript": "^1.0.2",
68
- "@microsoft/api-extractor": "^7.49.2",
68
+ "@microsoft/api-extractor": "^7.52.5",
69
69
  "@microsoft/tsdoc-config": "^0.17.1",
70
- "@mongodb-js/zstd": "^2.0.0",
70
+ "@mongodb-js/zstd": "^2.0.1",
71
71
  "@types/chai": "^4.3.17",
72
72
  "@types/chai-subset": "^1.3.5",
73
- "@types/express": "^4.17.21",
73
+ "@types/express": "^5.0.1",
74
74
  "@types/kerberos": "^1.1.5",
75
75
  "@types/mocha": "^10.0.9",
76
- "@types/node": "^22.13.0",
76
+ "@types/node": "^22.15.3",
77
77
  "@types/saslprep": "^1.0.3",
78
- "@types/semver": "^7.5.8",
79
- "@types/sinon": "^17.0.3",
80
- "@types/sinon-chai": "^3.2.12",
81
- "@types/whatwg-url": "^11.0.5",
82
- "@typescript-eslint/eslint-plugin": "8.4.0",
83
- "@typescript-eslint/parser": "8.4.0",
78
+ "@types/semver": "^7.7.0",
79
+ "@types/sinon": "^17.0.4",
80
+ "@types/sinon-chai": "^4.0.0",
81
+ "@types/whatwg-url": "^13.0.0",
82
+ "@typescript-eslint/eslint-plugin": "^8.31.1",
83
+ "@typescript-eslint/parser": "^8.31.1",
84
84
  "chai": "^4.4.1",
85
85
  "chai-subset": "^1.6.0",
86
86
  "chalk": "^4.1.2",
87
- "eslint": "9.9.0",
88
- "eslint-config-prettier": "^9.1.0",
87
+ "eslint": "^9.25.1",
88
+ "eslint-config-prettier": "^10.1.2",
89
89
  "eslint-plugin-mocha": "^10.4.1",
90
90
  "eslint-plugin-prettier": "^5.2.3",
91
91
  "eslint-plugin-simple-import-sort": "^12.1.1",
92
92
  "eslint-plugin-tsdoc": "^0.4.0",
93
93
  "eslint-plugin-unused-imports": "^4.1.4",
94
- "express": "^4.21.2",
94
+ "express": "^5.1.0",
95
95
  "gcp-metadata": "^5.3.0",
96
96
  "js-yaml": "^4.1.0",
97
97
  "mocha": "^10.8.2",
98
98
  "mocha-sinon": "^2.1.2",
99
- "mongodb-client-encryption": "^6.3.0",
99
+ "mongodb-client-encryption": "^6.4.0",
100
100
  "mongodb-legacy": "^6.1.3",
101
101
  "nyc": "^15.1.0",
102
- "prettier": "^3.4.2",
102
+ "prettier": "^3.5.3",
103
103
  "semver": "^7.7.0",
104
- "sinon": "^18.0.0",
104
+ "sinon": "^18.0.1",
105
105
  "sinon-chai": "^3.7.0",
106
106
  "snappy": "^7.2.2",
107
107
  "socks": "^2.8.1",
@@ -175,4 +175,4 @@
175
175
  "moduleResolution": "node"
176
176
  }
177
177
  }
178
- }
178
+ }
@@ -19,6 +19,7 @@ import { makeUpdateStatement, UpdateOperation, type UpdateStatement } from '../o
19
19
  import type { Server } from '../sdam/server';
20
20
  import type { Topology } from '../sdam/topology';
21
21
  import type { ClientSession } from '../sessions';
22
+ import { type Sort } from '../sort';
22
23
  import { type TimeoutContext } from '../timeout';
23
24
  import {
24
25
  applyRetryableWrites,
@@ -68,7 +69,7 @@ export interface DeleteManyModel<TSchema extends Document = Document> {
68
69
 
69
70
  /** @public */
70
71
  export interface ReplaceOneModel<TSchema extends Document = Document> {
71
- /** The filter to limit the replaced document. */
72
+ /** The filter that specifies which document to replace. In the case of multiple matches, the first document matched is replaced. */
72
73
  filter: Filter<TSchema>;
73
74
  /** The document with which to replace the matched document. */
74
75
  replacement: WithoutId<TSchema>;
@@ -78,11 +79,13 @@ export interface ReplaceOneModel<TSchema extends Document = Document> {
78
79
  hint?: Hint;
79
80
  /** When true, creates a new document if no document matches the query. */
80
81
  upsert?: boolean;
82
+ /** Specifies the sort order for the documents matched by the filter. */
83
+ sort?: Sort;
81
84
  }
82
85
 
83
86
  /** @public */
84
87
  export interface UpdateOneModel<TSchema extends Document = Document> {
85
- /** The filter to limit the updated documents. */
88
+ /** The filter that specifies which document to update. In the case of multiple matches, the first document matched is updated. */
86
89
  filter: Filter<TSchema>;
87
90
  /**
88
91
  * The modifications to apply. The value can be either:
@@ -98,6 +101,8 @@ export interface UpdateOneModel<TSchema extends Document = Document> {
98
101
  hint?: Hint;
99
102
  /** When true, creates a new document if no document matches the query. */
100
103
  upsert?: boolean;
104
+ /** Specifies the sort order for the documents matched by the filter. */
105
+ sort?: Sort;
101
106
  }
102
107
 
103
108
  /** @public */
@@ -252,7 +257,7 @@ export class BulkWriteResult {
252
257
  return this.result.writeErrors.length > 0;
253
258
  }
254
259
 
255
- /** Returns the number of write errors off the bulk operation */
260
+ /** Returns the number of write errors from the bulk operation */
256
261
  getWriteErrorCount(): number {
257
262
  return this.result.writeErrors.length;
258
263
  }
@@ -700,7 +705,7 @@ export class FindOperators {
700
705
 
701
706
  /** Add a single update operation to the bulk operation */
702
707
  updateOne(updateDocument: Document | Document[]): BulkOperationBase {
703
- if (!hasAtomicOperators(updateDocument)) {
708
+ if (!hasAtomicOperators(updateDocument, this.bulkOperation.bsonOptions)) {
704
709
  throw new MongoInvalidArgumentError('Update document requires atomic operators');
705
710
  }
706
711
 
@@ -1110,7 +1115,7 @@ export abstract class BulkOperationBase {
1110
1115
  ...op.updateOne,
1111
1116
  multi: false
1112
1117
  });
1113
- if (!hasAtomicOperators(updateStatement.u)) {
1118
+ if (!hasAtomicOperators(updateStatement.u, this.bsonOptions)) {
1114
1119
  throw new MongoInvalidArgumentError('Update document requires atomic operators');
1115
1120
  }
1116
1121
  return this.addToOperationsList(BatchType.UPDATE, updateStatement);
@@ -1124,7 +1129,7 @@ export abstract class BulkOperationBase {
1124
1129
  ...op.updateMany,
1125
1130
  multi: true
1126
1131
  });
1127
- if (!hasAtomicOperators(updateStatement.u)) {
1132
+ if (!hasAtomicOperators(updateStatement.u, this.bsonOptions)) {
1128
1133
  throw new MongoInvalidArgumentError('Update document requires atomic operators');
1129
1134
  }
1130
1135
  return this.addToOperationsList(BatchType.UPDATE, updateStatement);
@@ -52,6 +52,10 @@ export interface AutoEncryptionOptions {
52
52
  bypassAutoEncryption?: boolean;
53
53
  /** Allows users to bypass query analysis */
54
54
  bypassQueryAnalysis?: boolean;
55
+ /**
56
+ * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
57
+ */
58
+ keyExpirationMS?: number;
55
59
  options?: {
56
60
  /** An optional hook to catch logging messages from the underlying encryption engine */
57
61
  logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
@@ -285,6 +289,10 @@ export class AutoEncrypter {
285
289
  mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis;
286
290
  }
287
291
 
292
+ if (options.keyExpirationMS != null) {
293
+ mongoCryptOptions.keyExpirationMS = options.keyExpirationMS;
294
+ }
295
+
288
296
  this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis;
289
297
 
290
298
  if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) {
@@ -375,8 +383,8 @@ export class AutoEncrypter {
375
383
  /**
376
384
  * Cleans up the `_mongocryptdClient`, if present.
377
385
  */
378
- async teardown(force: boolean): Promise<void> {
379
- await this._mongocryptdClient?.close(force);
386
+ async close(): Promise<void> {
387
+ await this._mongocryptdClient?.close();
380
388
  }
381
389
 
382
390
  /**
@@ -885,6 +885,11 @@ export interface ClientEncryptionOptions {
885
885
  */
886
886
  tlsOptions?: CSFLEKMSTlsOptions;
887
887
 
888
+ /**
889
+ * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
890
+ */
891
+ keyExpirationMS?: number;
892
+
888
893
  /**
889
894
  * @experimental
890
895
  *
@@ -275,7 +275,7 @@ export class StateMachine {
275
275
  // See docs on EMPTY_V
276
276
  result = EMPTY_V ??= serialize({ v: [] });
277
277
  }
278
- for await (const key of keys) {
278
+ for (const key of keys) {
279
279
  context.addMongoOperationResponse(serialize(key));
280
280
  }
281
281
 
@@ -34,6 +34,9 @@ export class AutomatedCallbackWorkflow extends CallbackWorkflow {
34
34
  // If the server fails for any other reason, do not clear the cache.
35
35
  if (this.cache.hasAccessToken) {
36
36
  const token = this.cache.getAccessToken();
37
+ if (!connection.accessToken) {
38
+ connection.accessToken = token;
39
+ }
37
40
  try {
38
41
  return await this.finishAuthentication(connection, credentials, token);
39
42
  } catch (error) {
@@ -66,6 +69,9 @@ export class AutomatedCallbackWorkflow extends CallbackWorkflow {
66
69
  if (credentials.username) {
67
70
  params.username = credentials.username;
68
71
  }
72
+ if (credentials.mechanismProperties.TOKEN_RESOURCE) {
73
+ params.tokenAudience = credentials.mechanismProperties.TOKEN_RESOURCE;
74
+ }
69
75
  const timeout = Timeout.expires(AUTOMATED_TIMEOUT_MS);
70
76
  try {
71
77
  return await Promise.race([this.executeAndValidateCallback(params), timeout]);
@@ -1,9 +1,7 @@
1
1
  import { addAzureParams, AZURE_BASE_URL } from '../../../client-side-encryption/providers/azure';
2
2
  import { MongoAzureError } from '../../../error';
3
3
  import { get } from '../../../utils';
4
- import type { MongoCredentials } from '../mongo_credentials';
5
- import { type AccessToken, MachineWorkflow } from './machine_workflow';
6
- import { type TokenCache } from './token_cache';
4
+ import type { OIDCCallbackFunction, OIDCCallbackParams, OIDCResponse } from '../mongodb_oidc';
7
5
 
8
6
  /** Azure request headers. */
9
7
  const AZURE_HEADERS = Object.freeze({ Metadata: 'true', Accept: 'application/json' });
@@ -17,39 +15,29 @@ const TOKEN_RESOURCE_MISSING_ERROR =
17
15
  'TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.';
18
16
 
19
17
  /**
20
- * Device workflow implementation for Azure.
21
- *
22
- * @internal
18
+ * The callback function to be used in the automated callback workflow.
19
+ * @param params - The OIDC callback parameters.
20
+ * @returns The OIDC response.
23
21
  */
24
- export class AzureMachineWorkflow extends MachineWorkflow {
25
- /**
26
- * Instantiate the machine workflow.
27
- */
28
- constructor(cache: TokenCache) {
29
- super(cache);
22
+ export const callback: OIDCCallbackFunction = async (
23
+ params: OIDCCallbackParams
24
+ ): Promise<OIDCResponse> => {
25
+ const tokenAudience = params.tokenAudience;
26
+ const username = params.username;
27
+ if (!tokenAudience) {
28
+ throw new MongoAzureError(TOKEN_RESOURCE_MISSING_ERROR);
30
29
  }
31
-
32
- /**
33
- * Get the token from the environment.
34
- */
35
- async getToken(credentials?: MongoCredentials): Promise<AccessToken> {
36
- const tokenAudience = credentials?.mechanismProperties.TOKEN_RESOURCE;
37
- const username = credentials?.username;
38
- if (!tokenAudience) {
39
- throw new MongoAzureError(TOKEN_RESOURCE_MISSING_ERROR);
40
- }
41
- const response = await getAzureTokenData(tokenAudience, username);
42
- if (!isEndpointResultValid(response)) {
43
- throw new MongoAzureError(ENDPOINT_RESULT_ERROR);
44
- }
45
- return response;
30
+ const response = await getAzureTokenData(tokenAudience, username);
31
+ if (!isEndpointResultValid(response)) {
32
+ throw new MongoAzureError(ENDPOINT_RESULT_ERROR);
46
33
  }
47
- }
34
+ return response;
35
+ };
48
36
 
49
37
  /**
50
38
  * Hit the Azure endpoint to get the token data.
51
39
  */
52
- async function getAzureTokenData(tokenAudience: string, username?: string): Promise<AccessToken> {
40
+ async function getAzureTokenData(tokenAudience: string, username?: string): Promise<OIDCResponse> {
53
41
  const url = new URL(AZURE_BASE_URL);
54
42
  addAzureParams(url, tokenAudience, username);
55
43
  const response = await get(url, {
@@ -62,8 +50,8 @@ async function getAzureTokenData(tokenAudience: string, username?: string): Prom
62
50
  }
63
51
  const result = JSON.parse(response.body);
64
52
  return {
65
- access_token: result.access_token,
66
- expires_in: Number(result.expires_in)
53
+ accessToken: result.access_token,
54
+ expiresInSeconds: Number(result.expires_in)
67
55
  };
68
56
  }
69
57
 
@@ -77,9 +65,9 @@ function isEndpointResultValid(
77
65
  ): token is { access_token: unknown; expires_in: unknown } {
78
66
  if (token == null || typeof token !== 'object') return false;
79
67
  return (
80
- 'access_token' in token &&
81
- typeof token.access_token === 'string' &&
82
- 'expires_in' in token &&
83
- typeof token.expires_in === 'number'
68
+ 'accessToken' in token &&
69
+ typeof token.accessToken === 'string' &&
70
+ 'expiresInSeconds' in token &&
71
+ typeof token.expiresInSeconds === 'number'
84
72
  );
85
73
  }