Docs Menu
Docs Home
/ / /
Node.js Driver

What's New

On this page

  • What's New in 6.9
  • What's New in 6.8
  • What's New in 6.7
  • What's New in 6.6
  • What's New in 6.5
  • What's New in 6.4
  • What's New in 6.3
  • What's New in 6.2
  • What's New in 6.1
  • What's New in 6.0
  • What's New in 5.9
  • What's New in 5.8
  • What's New in 5.7
  • What's New in 5.6
  • What's New in 5.5
  • What's New in 5.4
  • What's New in 5.3
  • What's New in 5.2
  • What's New in 5.1
  • What's New in 5.0
  • What's New in 4.17
  • What's New in 4.16
  • What's New in 4.15
  • What's New in 4.14
  • What's New in 4.13
  • What's New in 4.12
  • What's New in 4.11
  • What's New in 4.10
  • What's New in 4.9
  • What's New in 4.8
  • What's New in 4.7
  • What's New in 4.6
  • What's New in 4.5
  • What's New in 4.4
  • What's New in 4.3
  • What's New in 4.2
  • What's New in 4.1
  • What's New in 4.0
  • What's New in 3.7
  • What's New in 3.6

Learn what's new in:

  • Support for MongoDB Server 3.6 is deprecated and will be removed in a future driver release.

  • The driver natively supports explicit resource management for cursors and the MongoClient, ClientSession, and ChangeStream objects. When using a compatible Node.js version, you can implement explicit resource management by using the cursor.stream() method and GridFSDownloadStream class.

    To learn how to use explicit resource management, see the v6.9.0 Release Notes on GitHub. For more information about explicit resource management, see the ECMAScript Explicit Resource Management Proposal on GitHub.

  • If you're using Node.js 18.13 or later, you can pass the autoSelectFamily and autoSelectFamilyTimeout options to the MongoClient constructor. When the autoSelectFamily option is true, the driver automatically selects between an IPv4 or IPv6 connection. The autoSelectFamilyTimeout option specifies the timeout, in milliseconds, for the driver to select the connection family.

    The following code example shows how to use these options:

    const client = new MongoClient(uri,
    { autoSelectFamily: true, autoSelectFamilyTimeout: 100 });
  • The MongoClient constructor accepts the allowPartialTrustChain option. This option controls the X509_V_FLAG_PARTIAL_CHAIN OpenSSL flag.

  • The ConnectionCheckedOutEvent and ConnectionCheckFailedEvent now include a durationMS property. This property indicates the time elapsed between the start and end of a connection checkout operation.

  • If you're using Node.js 18 or later, the driver ignores the cryptoCallbacks option and uses callbacks defined in C++ instead, significantly improving encryption performance. This change is available in the v6.1.0 version of the mongodb-client-encryption package.

  • To enhance security, the options specifying the spawn path and arguments for mongocryptd must be own properties of autoEncryption.extraOptions. This change helps prevent global prototype pollution bugs related to these options. For more information about own properties, see Object.hasOwn() on MDN.

  • Adds official support for Queryable Encryption (QE) range queries. To use this feature, your app must use mongodb-client-encryption v6.1.0 or later and must connect to MongoDB Server 8.0 or later. For more information about QE range queries, see Queryable Encryption in the MongoDB Server manual.

  • The insertMany() and bulkWrite() methods accept ReadonlyArray inputs.

  • The driver retries writes based on the top-level code, found in error.code, rather than the nested code in error.result.writeConcernError.code. This fixes an issue in sharded clusters running versions MongoDB Server earlier than 4.4.

  • The LocalKMSProviderConfiguration.key property accepts a BSON Binary instance for AutoEncryptionOptions.

  • In TypeScript, the BulkOperationBase class reports the length getter property.

  • The MongoWriteConcernError type now preserves the original top-level code in MongoWriteConcernError.code.

  • The cursor.toArray() method empties the current batch of documents into the array before calling the async iterator again. This change avoids the delays associated with async/await execution and improves performance by up to 5% on average. This optimization doesn't apply if you provide a transform to the cursor.map() method before calling the toArray() method.

  • Fixes mixed use of the cursor.next() method with for await syntax.

  • Adds the enableUtf8Validation option when deserializing BSON, which was inadvertently removed in Node.js driver v6.8.

  • Adds the durationMS property to the ConnectionReadyEvent class. This property represents the time between the connection creation event and when the ConnectionReadyEvent fires.

To learn more about this release, see the v6.9.0 Release Notes on GitHub.

The Node.js driver v6.8 release includes the following features:

  • Fixes a bug where a local KMS provider accepted a BSON Binary instance at runtime, but the TypeScript compiler allowed only values of type Buffer and string.

  • The ReadConcernMajorityNotAvailableYet error is now a retryable read error.

  • You can now associate a name with, and provide multiple keys for, KMS providers. This feature requires mongodb-client-encryption v6.0.1 or later. You can't use named KMS providers if your application uses the automatic KMS provider refresh capability.

    The following code example shows how to configure a ClientEncryption object with multiple AWS keys:

    const clientEncryption = new ClientEncryption(keyVaultClient, {
    'aws:key1': {
    accessKeyId: ...,
    secretAccessKey: ...
    },
    'aws:key2': {
    accessKeyId: ...,
    secretAccessKey: ...
    },
    clientEncryption.createDataKey('aws:key-1', { ... });
  • When you create a KMIP data key, you can now specify the delegated option. If this option is set to true, the KMIP provider performs encryption and decryption of the data key locally, ensuring that the encryption key never leaves the KMIP server. This feature requires mongodb-client-encryption v6.0.1 or later.

    The following code example shows how to specify this option:

    clientEncryption.createDataKey('kmip', { masterKey: { delegated: true } } );
  • The driver now decodes BSON responses as the cursor iterates over them, rather than decoding the entire BSON response when it is received.

  • The Github release for the mongodb package now contains a detached signature file, mongodb-X.Y.Z.tgz.sig, for the NPM package. This change applies to every major and patch release for versions 5.x and 6.x of the driver. To verify the package signature, follow the instructions in the Release Integrity section of the README.md file in the driver's GitHub repository.

To learn more about this release, see the v6.8.0 Release Notes on GitHub.

The Node.js driver v6.7 release includes the following features:

  • Adds support for the MONGODB-OIDC authentication mechanism when connected to MongoDB Server v7.0 and later. The driver supports authentication with Azure machine authentication, GCP machine authentication, callback authentication, and human interaction callback authentication facets.

  • Fixes an issue where setting the useBigInt64 flag to true caused the internal compareTopologyVersion function to generate an error.

To learn more about this release, see the v6.7.0 Release Notes on GitHub.

The Node.js driver v6.6 release includes the following features:

  • Upgrades to using BSON 6.7.0. For details about the new BSON features, see the release notes for BSON 6.5.0, BSON 6.6.0, and BSON 6.7.0.

  • Adds the addStage() method to the fluid aggregation API. You can use this method to add aggregation pipeline stages individually, as shown in the following example:

    const documents = await users.aggregate().addStage({ $project: { name: true } }).toArray();
  • Adds the cause and dependencyName fields to the MongoMissingDependencyError class. You can use these fields to programmatically determine if a package is missing or why a package didn't load.

  • Adds the minRoundTripTime property to the ServerDescription class. This property contains the minimum round-trip time over the last 10 heartbeats.

  • Adds the toJSON() method to the TopologyDescription class. Although you can use this method to stringify TopologyDescription objects to JSON, we recommend using Node's util.inspect() method instead, because it properly handles all types used in JavaScript and the driver.

  • Adds cursor options support for the Collection.indexExists(), Collection.indexes(), and Collection.indexInformation() methods in Typescript.

  • Removes support for the readConcern and writeConcern options from the Collection.listSearchIndexes() method. listSearchIndexes() is an Atlas-specific method, and Atlas search indexes don't support these options.

  • Redefines the ServerDescription.roundTripTime property as a moving average. Previously, it was a weighted average of the most recently observed heartbeat duration and the previous duration.

  • You can specify the type of a search index when creating the index, as shown in the following example:

    const indexName = await collection.createSearchIndex({
    name: 'my-vector-search-index',
    type: 'vectorSearch',
    definition: {
    mappings: { dynamic: false }
    }
    });
  • The UpdateFilter.$currentDate property no longer throws an error when you pass it to a compound method, such as findOneAndUpdate(), on a collection with a limited schema.

  • The driver throws a MongoTransactionError only if you provide a ReadPreferenceMode other than primary and then try to perform a command that involves a read operation.

  • The data type of the TopologyDescription.error property is MongoError.

  • The Collection.indexExists() method no longer supports the full option.

  • The Collection.indexInformation(), Collection.indexes(), and Db.indexInformation() methods have a return type of IndexDescriptionCompact | IndexDescriptionInfo[] in TypeScript.

  • When retrieving AWS KMS (Key Management System) credentials, the driver no longer throws an error when it receives an access key that includes an expiration timestamp.

  • The ClusterTime interface no longer defines the signature field as required in TypeScript.

To learn more about this release, see the v6.6.0 Release Highlights on GitHub.

The Node.js driver v6.5 release includes the following features:

  • Updates bulk write operations to use the pkFactory class for document ID generation.

Warning

If you previously specified an instance of a pkFactory to handle bulk writes, the _id fields of the documents inserted by using bulk writes may be inconsistent with the behavior in this version.

  • Fixes the read preference that is sent with read operations to primaryPreferred when the driver is connected to a secondary node in the replica set.

  • Fixes a memory leak in promise creation for socket operations.

  • Reduces first-time connection latency when connecting to a DNS seedlist by querying the SRV and TXT records in parallel.

  • Adds tracking to container metadata when running a client in Kubernetes or a container environment in the client.env.container field of the handshake document.

  • Adds the original error document returned by the server to the errorResponse field of the MongoServerError document.

  • Deprecates the CloseOptions interface which is unused by the driver.

To learn more about this release, see the v6.5.0 Release Highlights on GitHub.

The Node.js driver v6.4 release includes the following features:

  • When multiple mongos instances are available, different servers are used for read and write retry attempts.

  • Caches AWS credentials at the client level, rather than for each authentication.

  • Upgrades to using BSON 6.4.0. For details about the new BSON features, see the release notes for BSON 6.3.0 and BSON 6.4.0.

  • Read operations that result in an ExceededTimeLimit error are retried.

  • Fixes a request issue related to TLS sockets and KMS Providers.

  • Fixes the base64 padding on the saslContinue command to allow for mongosh authentication.

  • Types countDocuments using Filter<Schema> rather than Document, which enables autocompletion and helps prevent downstream typing issues.

  • Fixes a type error in the $addToSet option of the bulkWrite command. The driver skips $addToSet validation you extend your types from Document or any, or use properties of any type.

  • Fixes the ServerHeartbeatSucceeded and ServerHeartbeatFailed event heartbeat duration so that it does not include the time to create the socket.

  • Appropriately emits errors from cursor transform streams, rather than absorbing them.

  • Makes AWS session tokens optional when a username and password are provided, and allows AWS SDK to handle the authentication requests.

To learn more about this release, see the v6.4.0 Release Highlights on GitHub.

The Node.js driver v6.3 release includes the following features:

  • Adds the serverMonitoringMode client option to control the behavior of the monitoring connection among the nodes in a topology. This option takes a value of auto (default), poll, or stream. To learn more, see the entry for this option in the Connection Options guide.

    You can set the serverMonitoringMode option in a MongoClientOptions instance or as a connection string option. The following example shows how to create a client with the option set to stream:

    new MongoClient('<connection string>', { serverMonitoringMode: 'stream' });
  • Fixes a connection leak when the serverApi client option is set.

  • Deprecates the contentType and aliases GridFS options. To store the content type and aliases of a file, add contentType and aliases fields to the metadata document.

To learn more about this release, see the v6.3.0 Release Highlights.

The Node.js driver v6.2 release includes the following features:

  • Updates the bson package version to 6.2.0 to include color visualization of types, as shown in the following image:

    A screenshot of the terminal that shows printing in color

    To learn more, see the bson v6.2.0 release notes.

  • Ensures that the result.insertedIds property of a bulk write error type contains the _id values of successfully inserted documents. In previous versions, when a bulk write operation rejected an insert operation, the result.insertedIds property contained the _id values for all attempted inserts.

  • Closes the implicit session created when running the findOne() method on a time series collection regardless of the outcome of the operation.

  • Allows the creation of collections that have names that start or end with the . character. This change aligns the driver's database and collection name-checking behavior with the server's.

To learn more about this release, see the v6.2.0 Release Highlights.

The Node.js driver v6.1 release includes the following features:

  • Updates the bson package version to 6.1.0 to expose the Decimal128.fromStringWithRounding() method. To learn more, see the v6.1.0 bson release notes.

  • Detects environment variables for region settings when authenticating by using the MONGODB-AWS authentication mechanism. To instruct the driver to use your region options, you must set both of the following environment variables:

    • AWS_STS_REGIONAL_ENDPOINTS

    • AWS_REGION

  • Fixes a memory leak issue caused by recursive calls to the next() method of the ChangeStream type.

To learn more about this release, see the v6.1.0 Release Highlights.

Warning

Breaking Changes in v6.0

This driver version introduces breaking changes. For a list of these changes, see the Version 6.0 Breaking Changes section in the Upgrade guide.

The Node.js driver v6.0 release includes the following features:

Important

Deprecation Notice

All of the ssl-prefixed options in the MongoClientOptions type are deprecated. In addition, the tlsCertificateFile option is deprecated.

Instead, you should store your certificates in a SecureContext object or set the tls-prefixed options in your MongoClientOptions instance. To learn more, see Enable TLS on a Connection.

  • Removal of support for the addUser() helper command. Use the createUser MongoDB Shell command instead.

  • Removal of support for the collStats operation. Use the $collStats aggregation operator instead.

  • The options field of the ConnectionPoolCreatedEvent type contains only the following fields, which are the non-default pool options:

    • maxConnecting

    • maxPoolSize

    • minPoolSize

    • maxIdleTimeMS

    • waitQueueTimeoutMS

  • The driver asynchronously reads files set in the tlsCAFile and tlsCertificateKeyFile connection options when you call the MongoClient.connect() method, not when you create a MongoClient instance.

  • Removal of the keepAlive and keepAliveInitialDelay connection options. The value of keepAlive is permanently set to true and the value of keepAliveInitialDelay is set to 300000 milliseconds (300 seconds).

    To learn how to set keepalive settings at a system level, see the Does TCP keepalive time affect MongoDB Deployments? FAQ entry in the Server manual.

  • Removes the following options for the Db.command() method:

    • willRetryWrite

    • omitReadPreference

    • writeConcern

    • explain

    • readConcern

    • collation

    • maxTimeMS

    • comment

    • retryWrites

    • dbName

    • authdb

    • noResponse

    Although you cannot pass these options to the Db.command() method, you can still set them in the command document. To learn more, see the Command Options section of the Run a Command guide.

To learn more about this release, see the v6.0.0 Release Highlights.

Important

Upgrade from v5.8 to v5.9

This version includes a fix to a memory leak introduced in v5.7. We recommend upgrading to v5.9.

The Node.js driver v5.9 release includes the following features:

  • Fixed a memory leak introduced in v5.7.

  • The Decimal128 constructor and fromString() methods now throw an exception when they detect a loss of precision of more than 34 significant digits. The Decimal128 class exposes a new fromStringWithRounding() static method that uses the rounding behavior from previous versions of the driver. For more information, see the Release Notes for v5.5 of the js-bson package on GitHub.

  • Added support for detecting the AWS_STS_REGIONAL_ENDPOINTS and AWS_REGION environment variables and setting the appropriate options when calling the fromNodeProviderChain() method in the AWS SDK.

To learn more about this release, see the v5.9.0 Release Highlights.

Important

Upgrade from v5.8 to v5.9

This version includes a fix to a memory leak introduced in v5.7. We recommend upgrading to v5.9.

The Node.js driver v5.8 release includes the following features:

Important

Deprecation Notice

The AutoEncrypter interface is deprecated.

  • Support for Kerberos versions 1.x and 2.x.

  • Deprecation errors are not emitted for the tlsCertificateFile property when you set the tlsCertificateKeyFile property.

  • Removes credential availability in the ConnectionPoolCreatedEvent type. You can still access credentials through the credentials property of a MongoOptions instance.

  • Lowers the @aws-sdk/credential-providers version to 3.188.0 and zstd to ^1.0.0.

To learn more about this release, see the v5.8.0 Release Highlights.

The Node.js driver v5.7 release includes the following features:

Important

Deprecation Notice

  • The following Write Concern options are deprecated:

    • wtimeout

    • j

    • fsync

    To specify the write concern behavior, use the wtimeoutMS and journal options instead. To learn more about these options, see the Connection Options page.

  • SSL options and other transport encryption options are deprecated. To learn more about the deprecated options and which options to use instead, see the Legacy SSL options deprecated section in the v5.7.0 Release Highlights linked at the end of this section.

  • A new option for compound operation methods. The includeResultMetaData option allows you to specify whether to include information about the operation result. See the Built-in Methods section of the Compound Operations guide for more information.

  • Support for change stream split events which enables processing change stream documents that exceed the 16MB maximum BSON size limit.

  • An API to manage Search indexes from within your application. To learn more, see Search Indexes.

To learn more about this release, see the v5.7.0 Release Highlights.

The Node.js driver v5.6 release includes the following features:

To learn more about this release, see the v5.6.0 Release Highlights.

New features of the 5.5 Node.js driver release include:

  • The driver now accurately detects Function-as-a-Service (FaaS) environments in AWS by considering AWS environment variables only if they begin with AWS_Lambda_.

  • You must upgrade mongodb-client-encryption to version 2.8.0 or later if you want to create an encrypted collection by using the Queryable Encryption feature.

To learn more about this release, see the v5.5.0 Release Highlights.

New features of the 5.4 Node.js driver release include:

Important

Deprecation Notice

  • The collStats operation is deprecated. Use the $collStats aggregation operator instead.

  • The TypeScript interface passed to the db.command() method incorrectly includes certain options. These options have been deprecated.

  • The ChangeStream.tryNext method now uses the schema-specific TChange generic type instead of the Document interface.

To learn more, see the v5.4.0 Release Highlights.

New features of the 5.3 Node.js driver release include:

Important

Deprecation Notice

  • The forEach() cursor method, which allows you to iteratively access results from queries and aggregations, is deprecated. Use the for await...of syntax instead, as shown here.

  • The addUser() method is deprecated. Use createUser() instead.

  • The keepAlive and keepAliveInitialDelay connection options are deprecated.

  • Methods that contain duplicated functionality in the BulkWriteResult class are deprecated. See the API documentation for a full list of deprecated methods and the preferred alternatives.

  • Client metadata now includes function as a service (FaaS) environment information and alternative runtime detection.

  • The driver now allows SRV record addresses that contain a trailing dot.

  • UpdateResult.upsertedId now returns null when no documents are updated.

To learn more, see the v5.3.0 Release Highlights.

New features of the 5.2 Node.js driver release include:

  • The driver now supports automatically obtaining Azure credentials when using automatic Queryable Encryption.

To learn more, see the v5.2.0 Release Highlights.

New features of the 5.1 Node.js driver release include:

  • The driver now supports automatic serialization of JavaScript bigint to BSON.Long. It also supports the deserialization of BSON.Long values returned from the server to bigint values when the useBigInt64 flag is passed as true.

To learn more, see the v5.1.0 Release Highlights.

Warning

Breaking Changes in v5.0

This driver version introduces breaking changes. For a list of these changes, see the Version 5.0 Breaking Changes section in the Upgrade guide.

New features of the 5.0 Node.js driver release include:

  • By default, the driver no longer checks types referenced in dot notation unless the StrictFilter type annotation is explicitly used. To learn more about this change, see the Typescript fundamentals page.

    Note

    This change is for Typescript only, and does not affect queries or operations at runtime.

  • Optional installation of @aws-sdk/credential-providers as a peer dependency.

    • The driver no longer includes AWS SDK modules by default. Use the following npm command to install the SDK:

      npm install --save "@aws-sdk/credential-providers@^3.201.0"

      If you install the SDK, npm notifies you if the version of the SDK you installed is incompatible with the driver. Once you install the dependency successfully, the driver uses the AWS SDK itself to manage credentials from the environment.

New features of the 4.17 Node.js driver release include:

  • Adds the mongodb-js/saslprep package as a driver dependency.

  • Improves compatibility with the Queryable Encryption feature.

To learn more, see the v4.17.0 Release Highlights.

New features of the 4.16 Node.js driver release include:

  • Includes Function-as-a-Service (FaaS) platform information in the driver handshake metadata.

  • Identifies Deno runtime usage in the client metadata.

To learn more, see the v4.16.0 Release Highlights.

New features of the 4.15 Node.js driver release include:

  • Support for AWS IAM roles for service accounts.

To learn more, see the v4.15.0 Release Highlights.

Important

Upgrade from v4.13 to v4.14

This version includes a fix to a memory leak introduced in v4.13. We recommend upgrading to v4.14.

New features of the 4.14 Node.js driver release include:

  • Fixed a memory leak introduced in v4.13.

  • Deprecated methods and options that reference the legacy Logger.

New features of the 4.13 Node.js driver release include:

  • Automatic cancellation of in-flight operations in the connection pool when the driver encounters network timeout errors.

  • Disabled causal consistency in implicit sessions to prevent conflicting with the linearizable and available read concern settings.

  • Fixed a potential memory leak by ensuring that the driver destroys MessageStream instances whenever their connections are destroyed.

Important

Upgrade Driver to Version 4.12.1

The 4.12.1 Node.js driver includes a fix to a regression in monitoring logic that could cause processes to crash.

New features of the 4.12 Node.js driver release include:

  • Redefinition of the ChangeStream class as an async iterable. You can use ChangeStream instances in any context that expects an AsyncIterator.

    • Notably, change streams can now be used in Javascript for-await loops:

      const changeStream = myColl.watch();
      for await (const change of changeStream) {
      console.log("Received change: ", change);
      }
  • Fix to server monitoring when the driver skips monitoring events. In this release, the driver always updates its view of the topology when processing monitoring events.

  • Performance improvements with buffering as a result of modification to data structures used internally in the driver.

To learn more, see the v4.12.0 Release Highlights.

When connecting to MongoDB Server version 6.0 or later, the driver prioritizes electionId settings before setVersion settings during Server Discovery and Monitoring events. In previous versions, the prioritization order was reversed.

When you install the optional aws-sdk/credential-providers dependency, the driver uses the AWS SDK to retrieve AWS credentials from the environment.

To learn more about this behavior, see the MONGODB-AWS section of the Authentication Mechanisms guide.

This release includes added support for mutually recursive collection schema types. The driver also provides type safety for dot-notation queries up to a depth of eight in this release. At a depth greater than or equal to eight, Typescript successfully compiles your code but does not provide type safety. This depth limit on recursive types is a current limitation of TypeScript.

Suppose we have a collection of type Collection<Author> that contains the following mutually recursive types:

interface Author {
name: string;
bestBook: Book;
}
interface Book {
title: string;
author: Author;
}

TypeScript enforces type checking up to a depth of eight. The following code causes a TypeScript compilation error because the name property value must be a string type:

myColl.findOne({ 'bestBook.author.bestBook.title': 25 });

At a depth greater than or equal to eight, TypeScript compiles your code but no longer type checks it. For example, the following code assigns a number to a string property but does not cause a compilation error because the referenced property is at a depth of 10:

myColl.findOne({
'bestBook.author.bestBook.author.bestBook.author.bestBook.author.bestBook.author.name': 25
});

To learn more, see the v4.11.0 Release Highlights.

New features of the 4.10 Node.js driver release include:

  • Callback Deprecation

    • Callbacks are now deprecated in favor of Promises. Callbacks will be removed in the next major release. The Node driver team recommends migrating to promises where possible:

      • Use async/await syntax.

      • Use the Node.js callbackify utility:

        require('util').callbackify(() => myColl.findOne())(callback)
      • Use then syntax:

        myColl.findOne().then(res => callback(null, res), err => callback(err))
    • If you are unable to migrate to Promises in a large codebase, you can use the legacy Node.js driver with optional callback support.

To learn more, see v4.10.0 Release Highlights.

New features of the 4.9 Node.js driver release include:

  • Fixed an inconsistency with writeConcern options in the type definitions.

  • Included the latest BSON release, which adds automatic UUID support. See the BSON release notes here.

To learn more, see v4.9.0 Release Highlights.

Important

Upgrade from v4.8.0 to v4.8.1

Version 4.8.1 fixes a type regression issue introduced in v4.8.0. By upgrading to v4.8.1, you can specify _id values and sub-documents when performing updates with the $set or $setOnInsert operators.

New features of the 4.8 Node.js driver release include:

  • Added auto-completion and type safety for nested keys in an update filter

  • client.startSession() can now be called before connecting to MongoDB

  • estimatedDocumentCount() method can now accept a comment

To learn more, see v4.8.0 Release Highlights.

New features of the 4.7 Node.js driver release include:

  • The MongoClient.connect() method is now optional when connecting to your MongoDB instance

  • Ability to compress messages with the Zstandard compression algorithm

  • Added support for the maxConnecting connection option

  • Ability for change stream documents to show your documents before and after an update

  • Added support for new change stream fields related to Cluster to Cluster Replication

  • The estimatedDocumentCount() method now uses the $count database command

  • Improved connecting to MongoDB in the AWS Lambda Init phase

Important

Deprecation Notice

The ResumeOptions interface is deprecated. Use the ChangeStreamCursorOptions interface instead.

New features of the 4.6 Node.js driver release include:

  • Improved the ChangeStreamDocument in TypeScript.

  • Even distribution of server selection based on load across servers.

To learn more, see v4.6.0 Release Highlights.

See v4.5.0 Release Highlights on GitHub.

New features of the 4.4 Node.js driver release include:

  • KMIP provider support when using CSFLE.

  • TLS support when using CSFLE.

  • Hostname canonicalization now accepts "none", "forward", and "forwardAndReverse" as authMechanismProperties when using GSSAPI.

  • In the 4.0.0 release of the driver, the deprecated collection.count() method was inadvertently changed to behave like collection.countDocuments(). In this release, the collection.count() method is updated to match legacy behavior:

    • If a query is provided, collection.count() behaves the same as collection.countDocuments() and performs a collection scan.

    • If no query is provided, collection.count() behaves the same as collection.estimatedDocumentCount() and relies on collection metadata.

    Important

    Deprecation Notice

    The cursor.count() method is deprecated and will be removed in the next major version, along with collection.count(). Use the collection.estimatedDocumentCount() or collection.countDocuments() methods instead.

New features of the 4.3 Node.js driver release include:

New features of the 4.2 Node.js driver release include:

New features of the 4.1 Node.js driver release include:

  • Added load balanced connection support for all cluster types including the beta Serverless platform.

  • Added support for the advanceClusterTime() method to determine if the ClientSession should update its cluster time.

Warning

Breaking Changes in v4.0

This driver version introduces breaking changes. For a list of these changes, see the Version 4.0 Breaking Changes section in the Upgrade guide.

New features of the 4.0 Node.js driver release include:

Important

In this release of the driver, the deprecated collection.count() method was inadvertently changed to behave like collection.countDocuments(). This behavior is corrected in version 4.4.

  • We've migrated the driver to TypeScript. You can now harness the type hinting and intellisense features in editors that support it to develop your MongoDB applications. Enjoy the benefits of this work in pure JavaScript projects as well.

  • The underlying BSON library used by this version is now migrated to TypeScript.

  • Inline documentation is now consistently formatted to improve display in editors.

  • If you are a user of the community types @types/mongodb, there will likely be issues adopting the types from our codebase. We could not achieve a one to one match in types due to the details of writing the codebase in TypeScript.

We'd love to hear your TypeScript related feature requests. Please submit ideas on our JIRA project here.

The minimum supported version of Node.js is now v12.9 or greater for version 4 of the driver. Support for our 3.x branches will continue until mid-year 2022 to allow time for users to upgrade.

Note

3.x supports back to Node.js v4.

Our Cursor implementation is now updated to make it clear what is possible before and after execution of an operation.

Example

const fc = myColl.find({a: 2.3}).skip(1)
for await (const doc of fc) {
console.log(doc)
fc.limit(1) // incorrect usage, cursor already executing
}

There was inconsistency surrounding how the cursor would error if a setting was applied after cursor execution began. Now, the cursor will throw an error when attempting to apply operations in an invalid state, similar to the following:

MongoError: Cursor is already initialized

  • Affected classes:

    • AbstractCursor

    • FindCursor

    • AggregationCursor

    • ChangeStreamCursor (This is the underlying cursor for ChangeStream)

    • ListCollectionsCursor

Our Cursor types no longer extend Readable directly. They must be transformed into a stream by calling cursor.stream().

Example

const cursor = myColl.find({});
const stream = cursor.stream();
stream.on("data", data => console.log);
stream.on("error", () => client.close());

Use hasNext() and next() for manual iteration. Use for await of syntax or any Promise helpers for asynchronous iteration.

With type hinting, you should find that options passed to a MongoClient are enumerated and discoverable. We've made a large effort to process all options in the driver to give early warnings about incompatible settings to get your app up and running in a correct state quickly.

  • checkServerIdentity is no longer checked before being passed to the underlying Node API. Previously, accepted values were false, or a function. Now, the argument must be a function. Specifying a boolean will result in an error being thrown.

  • It is no longer required to specify useUnifiedTopology or useNewUrlParser.

This method no longer supports a strict option, which returned an error if the collection did not exist. To assert the existence of a collection, use the listCollections() method instead.

Example

const collections = (await db.listCollections({}, { nameOnly: true })
.toArray()).map(
({name}) => name
);
if (!collections.includes(myNewCollectionName)) {
throw new Error(`${myNewCollectionName} doesn't exist`);
}

BulkWriteError is now renamed to MongoBulkWriteError.

When running bulk operations that make writes you can encounter errors depending on your settings. Import the new class name MongoBulkWriteError when testing for errors in bulk operations.

DB is no longer an EventEmitter. Listen for events directly from your MongoClient instance.

The Collection.group() helper, deprecated since MongoDB 3.4, is now removed. Use the aggregation pipeline $group operator instead.

  • gssapiServiceName is now removed. Use authMechanismProperties.SERVICE_NAME in the URI or as an option on MongoClientOptions.

    Example

    ?authMechanismProperties.SERVICE_NAME
    // or
    new MongoClient(url, { SERVICE_NAME: "alternateServiceName" })
  • Specifying username and password as options is only supported in the URI or as an option on MongoClientOptions.

    Example

    new MongoClient("mongodb://<db_username>:<db_password>@<host><port>")
    // or
    new MongoClient(url, { auth: { username: "<db_username>", password: "<db_password>" } })

The GridStore API (already deprecated in 3.x) is now replaced with GridFSBucket. For more information on GridFS, see the mongodb manual.

Below are some snippets that represent equivalent operations.

Example

// old way
const gs = new GridStore(db, filename, mode[, options])
// new way
const bucket = new GridFSBucket(client.db('test')[,options])

GridFSBucket uses the Node.js Stream API. You can replicate file seeking by using the start and end options, creating a download stream from your GridFSBucket.

Example

bucket.openDownloadStreamByName(filename, { start: 0, end: 100 })

Example

await client.connect();
const filename = 'test.txt'; // whatever local file name you want
const db = client.db();
const bucket = new GridFSBucket(db);
fs.createReadStream(filename)
.pipe(bucket.openUploadStream(filename))
.on('error', console.error)
.on('finish', () => {
console.log('done writing to db!');
bucket
.find()
.toArray()
.then(files => {
console.log(files);
bucket
.openDownloadStreamByName(filename)
.pipe(fs.createWriteStream('downloaded_' + filename))
.on('error', console.error)
.on('finish', () => {
console.log('done downloading!');
client.close();
});
});
});

Note

GridFSBucket does not need to be closed like GridStore.

Example

// old way
GridStore.unlink(db, name, callback);
// new way
bucket.delete(file_id);

File metadata that used to be accessible on the GridStore instance can be found by querying the bucket.

Example

const fileMetaDataList: GridFSFile[] = bucket.find({}).toArray();
  • We internally now only manage a unifiedTopology when you connect to a mongod. The differences between this and previous versions is detailed here.

  • It is no longer required to specify useUnifiedTopology or useNewUrlParser.

  • You must use the new directConnection option to connect to uninitialized replica set members.

Support is now added for fine-grained verbosity modes. You can learn more about each mode here.

The instrument() method is now removed. Use command monitoring instead. See our guide on command monitoring for more information.

New features of the 3.7 Node.js driver release include:

  • Added support for load balancer mode while enabling the useUnifiedTopology option

  • Added support for Stable API while enabling the useUnifiedTopology option

New features of the 3.6 Node.js driver release include:

  • Added support for the MONGODB-AWS authentication mechanism using Amazon Web Services (AWS) Identity and Access Management (IAM) credentials

  • The find() method supports allowDiskUse() for sorts that require too much memory to execute in RAM

  • The update() and replaceOne() methods support index hints

  • A reduction in recovery time for topology changes and failover events

  • Improvements in validation testing for the default writeConcern

  • Authentication requires fewer round trips to the server, resulting in faster connection setup

  • Shorter Salted Challenge Response Authentication Mechanism (SCRAM) conversations

  • Ability to create collections and indexes for multiple document transactions

  • Running validation for a collection in the background

Back

Quick Reference