Skip to content

v6.10.0

Compare
Choose a tag to compare
@github-actions github-actions released this 21 Oct 20:47
a275567

6.10.0 (2024-10-21)

The MongoDB Node.js team is pleased to announce version 6.10.0 of the mongodb package!

Release Notes

Warning

Server versions 3.6 and lower will get a compatibility error on connection and support for MONGODB-CR authentication is now also removed.

Support for new client bulkWrite API (8.0+)

A new bulk write API on the MongoClient is now supported for users on server versions 8.0 and higher.
This API is meant to replace the existing bulk write API on the Collection as it supports a bulk
write across multiple databases and collections in a single call.

Usage

Users of this API call MongoClient#bulkWrite and provide a list of bulk write models and options.
The models have a structure as follows:

Insert One

Note that when no _id field is provided in the document, the driver will generate a BSON ObjectId
automatically.

{
  namespace: '<db>.<collection>',
  name: 'insertOne',
  document: Document
}

Update One

{
  namespace: '<db>.<collection>',
  name: 'updateOne',
  filter: Document,
  update: Document | Document[],
  arrayFilters?: Document[],
  hint?: Document | string,
  collation?: Document,
  upsert: boolean
}

Update Many

Note that write errors occuring with an update many model present are not retryable.

{
  namespace: '<db>.<collection>',
  name: 'updateMany',
  filter: Document,
  update: Document | Document[],
  arrayFilters?: Document[],
  hint?: Document | string,
  collation?: Document,
  upsert: boolean
}

Replace One

{
  namespace: '<db>.<collection>',
  name: 'replaceOne',
  filter: Document,
  replacement: Document,
  hint?: Document | string,
  collation?: Document
}

Delete One

{
  namespace: '<db>.<collection>',
  name: 'deleteOne',
  filter: Document,
  hint?: Document | string,
  collation?: Document
}

Delete Many

Note that write errors occuring with a delete many model present are not retryable.*

{
  namespace: '<db>.<collection>',
  name: 'deleteMany',
  filter: Document,
  hint?: Document | string,
  collation?: Document
}

Example

Below is a mixed model example of using the new API:

const client = new MongoClient(process.env.MONGODB_URI);
const models = [
  {
    name: 'insertOne',
    namespace: 'db.authors',
    document: { name: 'King' }
  },
  {
    name: 'insertOne',
    namespace: 'db.books',
    document: { name: 'It' }
  },
  {
    name: 'updateOne',
    namespace: 'db.books',
    filter: { name: 'it' },
    update: { $set: { year: 1986 } }
  }
];
const result = await client.bulkWrite(models);

The bulk write specific options that can be provided to the API are as follows:

  • ordered: Optional boolean that indicates the bulk write as ordered. Defaults to true.
  • verboseResults: Optional boolean to indicate to provide verbose results. Defaults to false.
  • bypassDocumentValidation: Optional boolean to bypass document validation rules. Defaults to false.
  • let: Optional document of parameter names and values that can be accessed using $$var. No default.

The object returned by the bulk write API is:

interface ClientBulkWriteResult {
  // Whether the bulk write was acknowledged.
  readonly acknowledged: boolean;
  // The total number of documents inserted across all insert operations.
  readonly insertedCount: number;
  // The total number of documents upserted across all update operations.
  readonly upsertedCount: number;
  // The total number of documents matched across all update operations.
  readonly matchedCount: number;
  // The total number of documents modified across all update operations.
  readonly modifiedCount: number;
  // The total number of documents deleted across all delete operations.
  readonly deletedCount: number;
  // The results of each individual insert operation that was successfully performed.
  // Note the keys in the map are the associated index in the models array.
  readonly insertResults?: ReadonlyMap<number, ClientInsertOneResult>;
  // The results of each individual update operation that was successfully performed.
  // Note the keys in the map are the associated index in the models array.
  readonly updateResults?: ReadonlyMap<number, ClientUpdateResult>;
  // The results of each individual delete operation that was successfully performed.
  // Note the keys in the map are the associated index in the models array.
  readonly deleteResults?: ReadonlyMap<number, ClientDeleteResult>;
}

Error Handling

Server side errors encountered during a bulk write will throw a MongoClientBulkWriteError. This error
has the following properties:

  • writeConcernErrors: Ann array of documents for each write concern error that occurred.
  • writeErrors: A map of index pointing at the models provided and the individual write error.
  • partialResult: The client bulk write result at the point where the error was thrown.

Schema assertion support

interface Book {
  name: string;
  authorName: string;
}

interface Author {
  name: string;
}

type MongoDBSchemas = {
  'db.books': Book;
  'db.authors': Author;
}

const model: ClientBulkWriteModel<MongoDBSchemas> = {
  namespace: 'db.books'
  name: 'insertOne',
  document: { title: 'Practical MongoDB Aggregations', authorName: 3 } 
  // error `authorName` cannot be number
};

Notice how authorName is type checked against the Book type because namespace is set to "db.books".

Allow SRV hostnames with fewer than three . separated parts

In an effort to make internal networking solutions easier to use like deployments using kubernetes, the client now accepts SRV hostname strings with one or two . separated parts.

await new MongoClient('mongodb+srv://mongodb.local').connect();

For security reasons, the returned addresses of SRV strings with less than three parts must end with the entire SRV hostname and contain at least one additional domain level. This is because this added validation ensures that the returned address(es) are from a known host. In future releases, we plan on extending this validation to SRV strings with three or more parts, as well.

// Example 1: Validation fails since the returned address doesn't end with the entire SRV hostname
'mongodb+srv://mySite.com' => 'myEvilSite.com' 

// Example 2: Validation fails since the returned address is identical to the SRV hostname
'mongodb+srv://mySite.com' => 'mySite.com' 

// Example 3: Validation passes since the returned address ends with the entire SRV hostname and contains an additional domain level
'mongodb+srv://mySite.com' => 'cluster_1.mySite.com' 

Explain now supports maxTimeMS

Driver CRUD commands can be explained by providing the explain option:

collection.find({}).explain('queryPlanner'); // using the fluent cursor API
collection.deleteMany({}, { explain: 'queryPlanner' }); // as an option

However, if maxTimeMS was provided, the maxTimeMS value was applied to the command to explain, and consequently the server could take more than maxTimeMS to respond.

Now, maxTimeMS can be specified as a new option for explain commands:

collection.find({}).explain({ verbosity: 'queryPlanner', maxTimeMS: 2000 }); // using the fluent cursor API
collection.deleteMany({}, { 
	explain: {
		verbosity: 'queryPlanner',
		maxTimeMS: 2000
	}
); // as an option

If a top-level maxTimeMS option is provided in addition to the explain maxTimeMS, the explain-specific maxTimeMS is applied to the explain command, and the top-level maxTimeMS is applied to the explained command:

collection.deleteMany({}, { 
	maxTimeMS: 1000,
	explain: {
		verbosity: 'queryPlanner',
		maxTimeMS: 2000
	}
);

// the actual command that gets sent to the server looks like:
{
	explain: { delete: <collection name>, ..., maxTimeMS: 1000 },
    verbosity: 'queryPlanner',
	maxTimeMS: 2000 
}

Find and Aggregate Explain in Options is Deprecated

Note

Specifying explain for cursors in the operation's options is deprecated in favor of the .explain() methods on cursors:

collection.find({}, { explain: true })
// -> collection.find({}).explain()

collection.aggregate([], { explain: true })
// -> collection.aggregate([]).explain()

db.find([], { explain: true })
// -> db.find([]).explain()

Fixed writeConcern.w set to 0 unacknowledged write protocol trigger

The driver now correctly handles w=0 writes as 'fire-and-forget' messages, where the server does not reply and the driver does not wait for a response. This change eliminates the possibility of encountering certain rare protocol format, BSON type, or network errors that could previously arise during server replies. As a result, w=0 operations now involve less I/O, specifically no socket read.

In addition, when command monitoring is enabled, the reply field of a CommandSucceededEvent of an unacknowledged write will always be { ok: 1 }.

Fixed indefinite hang bug for high write load scenarios

When performing large and many write operations, the driver will likely encounter buffering at the socket layer. The logic that waited until buffered writes were complete would mistakenly drop 'data' (reading from the socket), causing the driver to hang indefinitely or until a socket timeout. Using pausing and resuming mechanisms exposed by Node streams we have eliminated the possibility for data events to go unhandled.

Shout out to @hunkydoryrepair for debugging and finding this issue!

Fixed change stream infinite resume

Before this fix, when change streams would fail to establish a cursor on the server, the driver would infinitely attempt to resume the change stream. Now, when the aggregate to establish the change stream fails, the driver will throw an error and clos the change stream.

ClientSession.commitTransaction() no longer unconditionally overrides write concern

Prior to this change, ClientSession.commitTransaction() would always override any previously configured writeConcern on the initial attempt. This overriding behaviour now only applies to internal and user-initiated retries of ClientSession.commitTransaction() for a given transaction.

Features

Bug Fixes

Documentation

We invite you to try the mongodb library immediately, and report any issues to the NODE project.