NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
crates.io, #2439 most downloaded on crates.io
The official MongoDB driver for Rust
Latest stable
3.10.2
Last release 3 days ago
19 Nov 2026
Ships fairly regularly
a new release about every 6 weeks
Nearly every release is documented
notes for 56 of the last 60 stable releases
1 version withdrawn
withdrawn after publishing
12 years old
106 releases · first in 2015
Drag across the ruler to compare, or tap a release to open it.
Nothing published for this version
Important This is a security patch release for CVE-2026-126838 . Upgrading is recommended for all users.
The MongoDB Rust driver team is pleased to announce the v3.10.1 release of the mongodb crate, now available for download from crates.io.
Important
This is a security patch release for CVE-2026-126838. Upgrading is recommended for all users.
Debug implsYour coding agent can read these notes before it upgrades. Set up the MCP server →
Important This is a security patch release for CVE-2026-120673 . Upgrading is recommended for all users.
The MongoDB Rust driver team is pleased to announce the v3.10.0 release of the mongodb crate, now available for download from crates.io.
Important
This is a security patch release for CVE-2026-120673. Upgrading is recommended for all users.
db.query.text attributeThis release fixes a bug that caused query documents to be recorded in Opentelemetry before automatic encryption was applied, potentially exposing the message plaintext.
Previous versions of the driver would allow the character '|' in client metadata; in order to preserve the mapping between versions and names in the final message, this is now not allowed and attempting to set or add metadata containing this character will result in an error.
This version of the driver now requires a minimum Rust compiler version of 1.94.1.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
Important This is a security patch release for CVE-2026-88024 . Upgrading is recommended for all users.
The MongoDB Rust driver team is pleased to announce the v3.9.1 release of the mongodb crate, now available for download from crates.io.
Important
This is a security patch release for CVE-2026-88024. Upgrading is recommended for all users.
This release fixes a bug that would allow certain inputs to delete all files in a GridFS bucket.
The MongoDB Rust driver team is pleased to announce the v3.9.0 release of the mongodb crate, now available for download from crates.io .
The MongoDB Rust driver team is pleased to announce the v3.9.0 release of the mongodb crate, now available for download from crates.io.
This release adds support for the new baseBackoffMS server error field. The driver now uses the value for baseBackoffMS reported by the server in its retry backoff calculations. This new feature is part of MongoDB's Intelligent Workload Management (IWM) and is available on MongoDB Atlas server versions 9.0+.
Important This is a security patch release for CVE-2026-81526 . Upgrading is recommended for all users.
The MongoDB Rust driver team is pleased to announce the v3.8.2 release of the mongodb crate, now available for download from crates.io.
Important
This is a security patch release for CVE-2026-81526. Upgrading is recommended for all users.
This release fixes a bug that would allow Client::bulk_write to write to a different database than the one specified in a write model's namespace.
The MongoDB Rust driver team is pleased to announce the v3.8.1 release of the mongodb crate, now available for download from crates.io .
The MongoDB Rust driver team is pleased to announce the v3.8.1 release of the mongodb crate, now available for download from crates.io.
This release fixes two bugs: a potential infinite loop in change streams, and the find_one_and_* methods not reporting errors in some circumstances.
Algorithm::TextPreview is deprecated in favor of Algorithm::String .
The MongoDB Rust driver team is pleased to announce the v3.8.0 release of the mongodb crate, now available for download from crates.io.
The string API for in-use encryption (previously named the text API) is now stable and GA! This brings with it the following changes:
text-indexes-unstable feature is no longer required to enable this API. The feature still exists for backwards compatibility but does nothing.TextOptions struct is now StringOptions.Algorithm::TextPreview is deprecated in favor of Algorithm::String."prefixPreview", "suffixPreview", and "substringPreview" are deprecated in favor of "prefix", "suffix", and "substring" respectively.The GA API requires mongodb server version 9.0. The preview API can continue to be used with pre-9.0 server versions.
As of this release, connecting to server version 4.2 is deprecated. Support for 4.2 will be removed in the 3.9.0 release.
MONGODB-AWS explicit authentication property deprecationThe use of explicit username, password, or the "AWS_SESSION_TOKEN" property with the MONGODB-AWS auth mechanism is deprecated, and will emit warnings when debug assertions are enabled. Support for these will be removed in version 4.0 of the driver.
A long-standing bug in the hickory-resolver case when running on Windows caused performance degredation when using a mongodb+srv connection string. Happily, this bug is now fixed, so users who previously used our recommended workaround of a custom DNS configuration on Windows can now remove that workaround.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.7.0 release of the mongodb crate, now available for download from crates.io .
The MongoDB Rust driver team is pleased to announce the v3.7.0 release of the mongodb crate, now available for download from crates.io.
This release updates the minimum supported rust compiler version to 1.88.
Due to a security advisory, the version of hickory used internally has been updated to 0.26. This should have no user-visible behavior impact.
Client::shutdown improvementsThe implementation of shutdown's wait for server resource cleanup and background task termination has been improved to be more consistent and cover more cases.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.6.0 release of the mongodb crate, now available for download from crates.io .
The MongoDB Rust driver team is pleased to announce the v3.6.0 release of the mongodb crate, now available for download from crates.io.
With 3.6.0, the client has a variety of changes to improve behavior when connected to overloaded servers, most notably retrying against a different server (if available). These features will be functional with MongoDB Atlas Server Version 9.0 and above.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.5.2 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.5.2 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.5.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.5.1 release of the mongodb crate, now available for download from crates.io.
This release removes a check added in 3.4.0 that would reject metadata containing the | character.
…field of the auth mechanism properties doc is deprecated; using these is almost never the correct setup and can lead to the driver losing connectivity…
The MongoDB Rust driver team is pleased to announce the v3.5.0 release of the mongodb crate, now available for download from crates.io.
3.5.0 includes the optional socks5-proxy feature, which enables connecting to the database via a SOCKS5 proxy. This can be configured either with the proxyHost, proxyPort, proxyUsername, and proxyPassword connection string options or the ClientOptions::socks5_proxy field.
This release adds support for iterating over the raw document batches returned by the server for cursors rather than individual deserialized values. For some applications, this can enable significant performance improvements; see the module documentation for more details.
Specifying AWS authentication properties via the username and password in URI strings and the AWS_SESSION_TOKEN field of the auth mechanism properties doc is deprecated; using these is almost never the correct setup and can lead to the driver losing connectivity. This functionality will be removed in the next major version of the driver.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.4.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.4.1 release of the mongodb crate, now available for download from crates.io.
The driver now includes helpers for building Atlas Search aggregation pipelines. See the documentation for more details and examples.
The driver now supports tracing database commands and driver operations for OpenTelemetry.
The driver now supports text indexes for both automatic and explicit encryption. Note that this feature is in preview and should only be used in experimental workloads. The text-indexes-unstable feature flag must be enabled to use text indexes. The GA version of this feature may not be backwards-compatible with the preview version.
Thank you to @tottoto and @FalkWoldmann for their several contributions to update and refine our dependencies!
Impactful changes are listed below; for a complete list of changes, see this GitHub query.
Display and Serialize for ConnectionString (#1494)Error (#1474)[!NOTE] Version 3.4.0 of the driver was skipped due to an issue in the release process.
With the stabilization of async closures, the convenient transaction API (StartTransaction::and_run) has been deprecated in favor of StartTransaction:…
The MongoDB Rust driver team is pleased to announce the v3.3.0 release of the mongodb crate, now available for download from crates.io.
bson 3.0This version of the driver provides the bson-3 feature, which allows opting in to use the 3.0 version of the bson crate where the driver API exposes those types. Any usage without that feature (e.g. all existing projects) will continue to use the 2.x version. See the bson 3.0 migration guide for more information.
With the stabilization of async closures, the convenient transaction API (StartTransaction::and_run) has been deprecated in favor of StartTransaction::and_run2, which provides the same functionality but without needing to box the closure or pass a distinct data argument.
The driver now supports the use of GSSAPI for authentication of driver connections on Linux, MacOS, and Windows.
The minimum server version supported by the driver is now 4.2; support for 4.0 was deprecated in driver version 3.2.0 and has now been removed.
Impactful changes are listed below; for a complete list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.2.5 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.5 release of the mongodb crate, now available for download from crates.io.
This release fixes a bug that caused the driver to allow invalid TLS certificates when the URI option "tlsInsecure=false" was included in the connection string.
The MongoDB Rust driver team is pleased to announce the v3.2.4 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.4 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.3 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.3 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.2 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.2 release of the mongodb crate, now available for download from crates.io.
RUST-2144 Remove use of deprecated openssl_probe method (#1294, #1297)
The MongoDB Rust driver team is pleased to announce the v3.2.1 release of the mongodb crate, now available for download from crates.io.
openssl_probe method (#1294, #1297)The MongoDB Rust driver team is pleased to announce the v3.2.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.2.0 release of the mongodb crate, now available for download from crates.io.
The API for in-use encryption is now stable and has the same backwards compatibility guarantees as the rest of the driver. To reflect this, the feature is now named in-use-encryption; in-use-encryption-unstable will continue to be provided as a compatibility alias. Please note that this is a policy change only and that the API itself has not changed from the previous release.
When looking at the rustdoc for methods with chainable setters for options (e.g. Collection::find), those setters are listed directly in the rustdoc for the method rather than only being visible in the rustdoc for the type of the returned future.
In the next minor version release (3.3.0), the Rust driver will be dropping support for connecting to mongodb server version 4.0. As of that release, the minimum supported server version will be 4.2.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v3.1.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.1.1 release of the mongodb crate, now available for download from crates.io.
derivative dependency (#1245)hickory dependencies (#1264)The MongoDB Rust driver team is pleased to announce the v3.1.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.1.0 release of the mongodb crate, now available for download from crates.io.
This release provides compatibility with MongoDB 8.0, including support for a number of new in-use encryption features.
The MongoDB Rust driver team is pleased to announce the v3.0.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v3.0.1 release of the mongodb crate, now available for download from crates.io.
This release fixes two bugs:
Collection::watch didn't use the Collection's type parameterFor detailed information on breaking changes and examples of migrating from 2.x to 3.0, please see the migration guide.
The MongoDB Rust driver team is pleased to announce the v3.0.0 release of the mongodb crate, now available for download from crates.io.
3.0 introduces a wide variety of improvements that required backwards-incompatible API changes; in most cases these changes should require only minor updates in application code.
Most notably:
EventHandler type, which can be constructed from a callback, async callback, or an async channel sender.tokio; support for async-std has been discontinued.For detailed information on breaking changes and examples of migrating from 2.x to 3.0, please see the migration guide.
The Rust driver now implements the new Bulk Write specification, which supports performing mixed write operations against multiple namespaces in a minimized number of round-trips to the server. This feature is only available for early testing using MongoDB 8.0 release candidate binaries. This feature is not recommended for use in production until the stable release of MongoDB 8.0.
The Rust driver can now authenticate using an OpenID Connect access token, including support for both the machine and human authentication flows, and automatic token acquisition for Azure and GCP.
Below are a selected list of other changes with user impact; for a full list of changes see this GitHub query.
For detailed information on breaking changes and examples of migrating from 2.x to 3.0, please see the migration guide.
The MongoDB Rust driver team is pleased to announce the v3.0.0-beta release of the mongodb crate, now available for download from crates.io.
3.0 introduces a wide variety of improvements that required backwards-incompatible API changes; in most cases these changes should require only minor updates in application code.
Most notably:
EventHandler type, which can be constructed from a callback, async callback, or an async channel sender.tokio; support for async-std has been discontinued.For detailed information on breaking changes and examples of migrating from 2.x to 3.0, please see the migration guide.
The Rust driver now implements the new Bulk Write specification, which supports performing mixed write operations against multiple namespaces in a minimized number of round-trips to the server. This feature is only available for early testing using MongoDB 8.0 release candidate binaries. This feature is not recommended for use in production until the stable release of MongoDB 8.0.
The Rust driver can now authenticate using an OpenID Connect access token, including support for both the machine and human authentication flows, and automatic token acquisition for Azure and GCP.
Below are a selected list of other changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v2.8.2 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.8.2 release of the mongodb crate, now available for download from crates.io.
This release fixes a potential issue when serializing messages.
OP_MSG payload type 1) (#1009)The MongoDB Rust driver team is pleased to announce the v2.8.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.8.1 release of the mongodb crate, now available for download from crates.io.
This release fixes two bugs:
RUST-1763 deprecate CollectionOptions::human_readable_serialization
The MongoDB Rust driver team is pleased to announce the v2.8.0 release of the mongodb crate, now available for download from crates.io.
The Collection type now has the create_search_index, create_search_indexes, update_search_index, drop_search_index, and list_search_indexes methods, allowing comprehensive management of search indexes from client code.
More error types will be automatically retried, and retries will avoid mongos backends with network connectivity issues. Also note that the documentation for with_transaction has been updated to clarify error handling requirements to avoid a deadlock.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
Operation::build (#942)MSRV-Cargo.lock (#981) (thanks @stIncMale!)GetMoreProvider trait into a generic struct (#983) (thanks @stIncMale!)The MongoDB Rust driver team is pleased to announce the v2.7.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.7.1 release of the mongodb crate, now available for download from crates.io.
This release fixes a bug that caused a memory leak in various circumstances.
RUST-1763 deprecate CollectionOptions::human_readable_serialization
The MongoDB Rust driver team is pleased to announce the v2.7.0 release of the mongodb crate, now available for download from crates.io.
The Rust driver documentation is now hosted at https://www.mongodb.com/docs/drivers/rust/current/. This documentation includes detailed content about features, runnable examples, troubleshooting resources, and more.
When serializing values via serde, the serializer can indicate whether or not the target format is human-readable, allowing types to change behavior based on that. The Rust driver had inadvertently been serializing values given to find_one_and_replace and replace_one as human-readible when all other methods serialize as non-human-readible; this bug is fixed in 2.7.0, with those methods also serializing as non-human-readible.
However, it is potentially possible (if unlikely) that user code may rely on this bug. If your code does rely on human-readable serialization, you can specify that via the new human_readable_serialization field in CollectionOptions.
run_cursor_commandThe Rust driver provides the run_command method as a way for users to directly send bson commands to the server; this is particularly useful when the driver does not yet have support for a newly-added server command. However, using this with commands that return a cursor requires re-implementing the logic for cursor iteration, which can be tedious and error-prone. The new run_cursor_command method avoids those problems, directly returning a Cursor using the same iteration logic as other methods.
The Rust driver will now log SDAM events when using the tracing-unstable feature.
The Client type now provides three additional ways to shape behavior to fit your workload:
ClientOptions.max_connecting lets you specify how many "in flight" connections can be established in parallel. This was previously fixed at 2 and defaults to the same value.Client::warm_connection_pool will create new connections to bring the connection pool up to min_pool_size, which can provide more predictable performance in some circumstances.Client::shutdown will cleanly stop background tasks and wait for outstanding handles to be dropped. This is particularly useful when using event handlers that reference external resources, as otherwise those handlers may be invoked in a background task even after the Client has been dropped.Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
RUST-1763 deprecate CollectionOptions::human_readable_serialization
The MongoDB Rust driver team is pleased to announce the v2.7.0-beta.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.7.0-beta release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.7.0-beta release of the mongodb crate, now available for download from crates.io.
When serializing values via serde, the serializer can indicate whether or not the target format is human-readable, allowing types to change behavior based on that. The Rust driver had inadvertently been serializing values given to find_one_and_replace and replace_one as human-readible when all other methods serialize as non-human-readible; this bug is fixed in 2.7.0-beta, with those methods also serializing as non-human-readible.
However, it is potentially possible (if unlikely) that user code may rely on this bug, so out of an abundance of caution we are releasing this version as a beta. If your code does rely on human-readable serialization, you can specify that via the new human_readable_serialization field in CollectionOptions.
run_cursor_commandThe Rust driver provides the run_command method as a way for users to directly send bson commands to the server; this is particularly useful when the driver does not yet have support for a newly-added server command. However, using this with commands that return a cursor requires re-implementing the logic for cursor iteration, which can be tedious and error-prone. The new run_cursor_command method avoids those problems, directly returning a Cursor using the same iteration logic as other methods.
The Rust driver will now log SDAM events when using the tracing-unstable feature.
The Client type now provides three additional ways to shape behavior to fit your workload:
ClientOptions.max_connecting lets you specify how many "in flight" connections can be established in parallel. This was previously fixed at 2 and defaults to the same value.Client::warm_connection_pool will create new connections to bring the connection pool up to min_pool_size, which can provide more predictable performance in some circumstances.Client::shutdown will cleanly stop background tasks and wait for outstanding handles to be dropped. This is particularly useful when using event handlers that reference external resources, as otherwise those handlers may be invoked in a background task even after the Client has been dropped.Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v2.6.1 release of the mongodb crate, now available for download from crates.io. This release r
The MongoDB Rust driver team is pleased to announce the v2.6.1 release of the mongodb crate, now available for download from crates.io. This release removes a potential panic from the SessionCursor::with_type method.
SessionCursor::with_type is called (#928) (thank you @mlokr for this fix!)The MongoDB Rust driver team is pleased to announce the v2.6.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.6.0 release of the mongodb crate, now available for download from crates.io.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
FromStr for Namespace (#889)ConnectionInfo (#894)The MongoDB Rust driver team is pleased to announce the v2.5.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.5.0 release of the mongodb crate, now available for download from crates.io.
This release adds the ClientEncryption::create_encrypted_collection helper method, which will automatically create encryption keys as needed when creating a collection with the encrypted_fields option.
This release adds the ClientSession::with_transaction helper method, which will handle automatically creating, retrying, and committing or aborting a transaction.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v2.4.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.4.0 release of the mongodb crate, now available for download from crates.io.
This release brings support for Client-Side Field Level Encryption and Queryable Encryption. For detailed installation and usage instructions, please see the Encryption section of the driver manual. Please note that the API is currently unstable and may change in breaking ways in future releases.
This release adds support for GridFS, allowing storage and retrieval of files that exceed the BSON document size limit. Please see the documentation of the new gridfs module for more information.
This release can now use the streaming monitoring protocol with MongoDB 4.4+ servers, reducing the time it takes for the client to discover server state changes compared to the old polling protocol.
The driver now emits tracing events at points of interest. To consume these events, you must enable the driver’s tracing-unstable feature flag and either:
Subscriber in your application (see the tracing docs), ORlog-compatible logger in your application (see the log documentation for details), and enable a log compatibility feature flag for tracing, as detailed here.This API is considered unstable as the tracing crate has not reached 1.0 yet; future minor versions of the driver may upgrade the tracing dependency to a new version which is not backwards-compatible with Subscribers that depend on older versions of tracing.
Events will be emitted under the following targets:
mongodb::command: Events related to command execution starting, succeeding, or failing.mongodb::connection: Events related to the driver’s underlying connection pools and their connections.Future work will introduce events under additional targets and may add driver-defined tracing spans for intervals of interest.
The minimum supported Rust version (MSRV) for this crate is now Rust 1.57.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta.2 release of the mongodb crate, now available for download from crates.io. Please
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta.2 release of the mongodb crate, now available for download from crates.io. Please note that this is a beta release; the API for in-use encryption may change between this and the final 2.4.0 release.
This release fixes a bug that caused the documentation for in-use encryption not to render on docs.rs.
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta.1 release of the mongodb crate, now available for download from crates.io. Please
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta.1 release of the mongodb crate, now available for download from crates.io. Please note that this is a beta release; the API for in-use encryption may change between this and the final 2.4.0 release.
This release fixes a bug that could cause list_collections to fail when timeseries collections were present; see RUST-1576 for details.
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta release of the mongodb crate, now available for download from crates.io. Please no
The MongoDB Rust driver team is pleased to announce the v2.4.0-beta release of the mongodb crate, now available for download from crates.io. Please note that this is a beta release; the API for in-use encryption may change between this and the final 2.4.0 release.
This release brings support for Client-Side Field Level Encryption and Queryable Encryption. For detailed installation and usage instructions, please see the Encryption section of the driver manual. Please note that rewrapManyDataKey and automatic KMS credentials are not yet supported in the Rust driver.
This release adds support for GridFS, allowing storage and retrieval of files that exceed the BSON document size limit. Please see the documentation of the new gridfs module for more information.
This release can now use the streaming monitoring protocol with MongoDB 4.4+ servers, reducing the time it takes for the client to discover server state changes compared to the old polling protocol.
The driver now emits tracing events at points of interest. To consume these events, you must enable the driver’s tracing-unstable feature flag and either:
Subscriber in your application (see the tracing docs), ORlog-compatible logger in your application (see the log documentation for details), and enable a log compatibility feature flag for tracing, as detailed here.This API is considered unstable as the tracing crate has not reached 1.0 yet; future minor versions of the driver may upgrade the tracing dependency to a new version which is not backwards-compatible with Subscribers that depend on older versions of tracing.
Events will be emitted under the following targets:
mongodb::command: Events related to command execution starting, succeeding, or failing.mongodb::connection: Events related to the driver’s underlying connection pools and their connections.Future work will introduce events under additional targets and may add driver-defined tracing spans for intervals of interest.
The minimum supported Rust version (MSRV) for this crate is now Rust 1.57.
Below are a selected list of changes with user impact; for a full list of changes see this GitHub query.
The MongoDB Rust driver team is pleased to announce the v2.3.1 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.3.1 release of the mongodb crate, now available for download from crates.io.
This release fixes a bug that caused connection establishment when using async-std to be blocking, and another bug that would cause the driver to attempt to continue monitoring servers that were removed from the topology.
The MongoDB Rust driver team is pleased to announce the v2.3.0 release of the mongodb crate, now available for download from crates.io.
The MongoDB Rust driver team is pleased to announce the v2.3.0 release of the mongodb crate, now available for download from crates.io.
The following sections detail some of the major changes included in this release. For a full list of changes, see the Full Release Notes section below.
The minimum supported Rust version (MSRV) for this crate is now Rust 1.53.
This release adds support for a number of new features added in MongoDB 6.0, including change streams with document pre- and post-images and clustered collections.
MongoDB 6.0 is now GA and available for use on MongoDB Atlas, and can also be downloaded here. Release notes for MongoDB 6.0 can be found here.
mongodb::Collection::estimated_document_count implementation (RUST-1216)When adding support for MongoDB 5.0, the driver's implementation of estimated_document_count was changed from using the count command to the aggregate command with the $collStats aggregation stage. This change first appeared in our 2.0.0-alpha.1 release. This change inadvertently broke support for using this method on views, as they do not support using $collStats.
In this release, we have reverted that change, and estimated_document_count is now once again implemented using the count command.
Please note that due to an oversight, count was omitted from the MongoDB Stable API version 1 in MongoDB server versions 5.0.0-5.0.8 and 5.1.0-5.3.1. Consequently, users of the Stable API who use estimated_document_count are recommended to either upgrade their MongoDB clusters to 5.0.9+ or 5.3.2+ (if on Atlas), or to set ClientOptions.server_api.strict to false when constructing Clients.
ConnectionString typeRUST-1193 introduced a new public mongodb::options::ConnectionString type, which models a MongoDB connection string. This type can be used to parse a connection string and inspect and manipulate its contents, and to initialize a mongodb::options::ClientOptions, and in turn a mongodb::Client.
For example:
use mongodb::{
Client,
options::{ClientOptions, ConnectionString},
};
let mut conn_str = ConnectionString::parse("mongodb://localhost:27017/?appName=myApp1")?;
println!("{:?}", conn_str.app_name); // prints: Some("myApp1")
conn_str.app_name = Some("newAppName".to_string());
println!("{:?}", conn_str.app_name); // prints: Some("newAppName")
let options = ClientOptions::parse_connection_string(conn_str).await?;
let client = Client::with_options(options)?;
The differences between a ConnectionString and ClientOptions are that:
ConnectionString only contains client options that are universal across MongoDB drivers and can be set via a MongoDB connection string, whereas ClientOptions also contains Rust driver-specific options,mongodb+srv connection string, initializing a ClientOptions will perform SRV and TXT lookup, whereas initializing a ConnectionString will not. Note that if a ConnectionString is initialized and then used to construct a ClientOptions or a Client, SRV/TXT lookup will be performed at that time.Below are a selected list of tickets with user impact; for a full list of completed tickets see this Jira query.
commitTransaction retry sometimes fails with InvalidOptions errorServerDescriptionChangedEvents for servers with errors always emitted even when description does not changelet option for multiple CRUD commandsConnectionString typecomment option to EstimatedDocumentCountOptionswallTime in the change stream event outputmaxWireVersion for MongoDB 6.0estimated_document_countThe MongoDB Rust driver team is pleased to announce the v2.3.0-beta release of the mongodb crate.
The MongoDB Rust driver team is pleased to announce the v2.3.0-beta release of the mongodb crate.
The following sections detail some of the major changes included in this release. For a full list of changes, see the Full Release Notes section below.
The minimum supported Rust version (MSRV) for this crate is now Rust 1.53.
This release adds support for a number of new features added in MongoDB 6.0, including change streams with document pre- and post-images and clustered collections.
The latest release candidate for MongoDB 6.0 is currently available for download here as well as on MongoDB Atlas.
mongodb::Collection::estimated_document_count implementation (RUST-1216)When adding support for MongoDB 5.0, the driver's implementation of estimated_document_count was changed from using the count command to the aggregate command with the $collStats aggregation stage. This change first appeared in our 2.0.0-alpha.1 release. This change inadvertently broke support for using this method on views, as they do not support using $collStats.
In this release, we have reverted that change, and estimated_document_count is now once again implemented using the count command.
Please note that due to an oversight, count was omitted from the MongoDB Stable API version 1 in MongoDB server versions 5.0.0-5.0.8 and 5.1.0-5.3.1. Consequently, users of the Stable API who use estimated_document_count are recommended to either upgrade their MongoDB clusters to 5.0.9+ or 5.3.2+ (if on Atlas), or to set ClientOptions.server_api.strict to false when constructing Clients.
ConnectionString typeRUST-1193 introduced a new public mongodb::options::ConnectionString type, which models a MongoDB connection string. This type can be used to parse a connection string and inspect and manipulate its contents, and to initialize a mongodb::options::ClientOptions, and in turn a mongodb::Client.
For example:
use mongodb::{
Client,
options::{ClientOptions, ConnectionString},
};
let mut conn_str = ConnectionString::parse("mongodb://localhost:27017/?appName=myApp1")?;
println!("{:?}", conn_str.app_name); // prints: Some("myApp1")
conn_str.app_name = Some("newAppName".to_string());
println!("{:?}", conn_str.app_name); // prints: Some("newAppName")
let options = ClientOptions::parse_connection_string(conn_str).await?;
let client = Client::with_options(options)?;
The differences between a ConnectionString and ClientOptions are that:
ConnectionString only contains client options that are universal across MongoDB drivers and can be set via a MongoDB connection string, whereas ClientOptions also contains Rust driver-specific options,mongodb+srv connection string, initializing a ClientOptions will perform SRV and TXT lookup, whereas initializing a ConnectionString will not. Note that if a ConnectionString is initialized and then used to construct a ClientOptions or a Client, SRV/TXT lookup will be performed at that time.Below are a selected list of tickets with user impact; for a full list of completed tickets see this Jira query.
The MongoDB Rust driver team is pleased to announce the 2.2.2 release of the mongodb crate. This release fixes a performance regression introduced in
The MongoDB Rust driver team is pleased to announce the 2.2.2 release of the mongodb crate. This release fixes a performance regression introduced in 2.2.0 for large reads when using rustls. It also fixes a rare bug that can cause commitTransaction retries to fail.
AsyncRead and AsyncWrite traits (#669)
The MongoDB Rust driver team is pleased to announce the v2.2.1 release of the mongodb crate.
The MongoDB Rust driver team is pleased to announce the v2.2.1 release of the mongodb crate.
This release includes a single change that upgrades the version of our rustc_version_runtime dependency from 0.1.4 to 0.2.1. The older version of rustc_version_runtime would create a file in the crate's src directory as part of the build process, which meant building the crate would fail on read-only file systems such as that used by docs.rs in the documentation process.
The MongoDB Rust driver team is pleased to announce the v2.2.0 release of the mongodb crate.
The MongoDB Rust driver team is pleased to announce the v2.2.0 release of the mongodb crate.
The following sections detail some of the more important changes included in this release. For a full list of changes, see the Full Release Notes section below.
This release adds support for Change Streams, which allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them.
let mut change_stream = coll.watch(None, None).await?;
let coll_ref = coll.clone();
task::spawn(async move {
coll_ref.insert_one(doc! { "x": 1 }, None).await;
});
while let Some(event) = change_stream.next().await.transpose()? {
println!("operation performed: {:?}, document: {:?}", event.operation_type, event.full_document);
// operation performed: Insert, document: Some(Document({"x": Int32(1)}))
}
This release uses the new raw BSON types introduced in v2.2 of the bson crate for internal operations, boosting performance in certain circumstances. It also allows for zero-copy deserialization when working with cursors via the new Cursor::deserialize_current method:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Cat<'a> {
#[serde(borrow)]
name: &'a str
}
let coll = db.collection::<Cat>("cat");
let mut cursor = coll.find(None, None).await?;
while cursor.advance().await? {
println!("{:?}", cursor.deserialize_current()?);
}
This release updates the version of all dependencies used by the Rust driver to their most recent, which required an update of the MSRV to 1.51.
This release adds optional support for using OpenSSL for TLS streams via the new openssl-tls feature. Note that rustls is still required as a dependency in this case to avoid breaking backwards compatibility; this will be removed in a future major version release.
The MongoDB Rust driver team is pleased to announce the v2.2.0-beta release of the mongodb crate.
The MongoDB Rust driver team is pleased to announce the v2.2.0-beta release of the mongodb crate.
The following sections detail some of the more important changes included in this release. For a full list of changes, see the Full Release Notes section below.
This release adds support for Change Streams, which allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them.
let mut change_stream = coll.watch(None, None).await?;
let coll_ref = coll.clone();
task::spawn(async move {
coll_ref.insert_one(doc! { "x": 1 }, None).await;
});
while let Some(event) = change_stream.next().await.transpose()? {
println!("operation performed: {:?}, document: {:?}", event.operation_type, event.full_document);
// operation performed: Insert, document: Some(Document({"x": Int32(1)}))
}
This release uses the new raw BSON types introduced in v2.2 of the bson crate for internal operations, boosting performance in certain circumstances. It also allows for zero-copy deserialization when working with cursors via the new Cursor::deserialize_current method:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Cat<'a> {
#[serde(borrow)]
name: &'a str
}
let coll = db.collection::<Cat>("cat");
let mut cursor = coll.find(None, None).await?;
while cursor.advance().await? {
println!("{:?}", cursor.deserialize_current()?);
}
This release updates the version of all dependencies used by the Rust driver to their most recent, which required an update of the MSRV to 1.51.
This release adds optional support for using OpenSSL for TLS streams via the new openssl-tls feature. Note that rustls is still required as a dependency in this case to avoid breaking backwards compatibility; this will be removed in a future major version release.
The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release N…
The MongoDB Rust driver team is pleased to announce the v2.1.0 release of the mongodb crate. This release contains a number of new features, bug fixes, and improvements, most notably support for Atlas Serverless.
The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release Notes section below.
bson to v2.1.0The exported version of bson was updated to v2.1.0, which includes its own set of changes. Check out the bson release notes for more information.
This release introduces load balancer support to the Rust driver, which enables it to be used with Atlas Serverless. As part of that, the test suite of the driver was updated to include testing against live Atlas Serverless instances to ensure full compatibility.
This release adds optional support for compressing the messages sent between the driver and the server. The available compression algorithms are zstd, snappy, and zlib, and they can be enabled via the zstd-compression, snappy-compression, and zlib-compression feature flags respectively. By default, none of the feature flags are enabled.
let mut options = ClientOptions::parse("mongodb://localhost:27017").await?;
// the server will select the algorithm it supports from the list provided by the driver
options.compressors = Some(vec![
Compressor::Snappy,
Compressor::Zlib {
level: Default::default(),
},
Compressor::Zstd {
level: Default::default(),
},
]);
let client = Client::with_options(options)?;
let resp = client
.database("admin")
.run_command(
doc! {
"ping": 1
},
None,
)
.await?;
println!("{}", resp);
This release adds driver support for causal consistency and enables it by default on all ClientSessions. For more information on the guarantees provided by causal consistency, check out the MongoDB manual.
let options = SessionOptions::builder().causal_consistency(true).build();
let mut session = client.start_session(Some(options)).await?;
let coll_options = CollectionOptions::builder()
.read_concern(ReadConcern::majority())
.write_concern(WriteConcern::builder().w(Acknowledgment::Majority).build())
.build();
let collection = client
.database("foo")
.collection_with_options("bar", coll_options);
collection
.insert_one_with_session(doc! { "read": "me" }, None, &mut session)
.await?;
collection
.find_one_with_session(doc! { "read": "me" }, None, &mut session)
.await?
.expect("causal consistency guarantees we can read our own writes");
FromStr for ServerAddress (#458)TopologyClosedEvent is the last SDAM event emitted (#485)Debug output of ClientOptions (#512)Clone for Collection<T> even when T isn't Clone (#454)ServerAddress::parse for URI parsing (#471)Collection::clone_with_type (#467) (thanks @PhotonQuantum!)The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release N…
The MongoDB Rust driver team is pleased to announce the v2.1.0-beta release of the mongodb crate. This release is a preview of the upcoming v2.1.0 release, which will be functionally the same but may contain fixes for any bugs identified in this beta. This release contains a number of new features, bug fixes, and improvements, most notably support for Atlas Serverless.
The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release Notes section below.
bson to v2.1.0-betaThe exported version of bson was updated to v2.1.0-beta, which includes its own set of changes. Check out the bson release notes for more information.
This release introduces load balancer support to the Rust driver, which enables it to be used with Atlas Serverless. As part of that, the test suite of the driver was updated to include testing against live Atlas Serverless instances to ensure full compatibility.
This release adds optional support for compressing the messages sent between the driver and the server. The available compression algorithms are zstd, snappy, and zlib, and they can be enabled via the zstd-compression, snappy-compression, and zlib-compression feature flags respectively. By default, none of the feature flags are enabled.
let mut options = ClientOptions::parse("mongodb://localhost:27017").await?;
// the server will select the algorithm it supports from the list provided by the driver
options.compressors = Some(vec![
Compressor::Snappy,
Compressor::Zlib {
level: Default::default(),
},
Compressor::Zstd {
level: Default::default(),
},
]);
let client = Client::with_options(options)?;
let resp = client
.database("admin")
.run_command(
doc! {
"ping": 1
},
None,
)
.await?;
println!("{}", resp);
This release adds driver support for causal consistency and enables it by default on all ClientSessions. For more information on the guarantees provided by causal consistency, check out the MongoDB manual.
let options = SessionOptions::builder().causal_consistency(true).build();
let mut session = client.start_session(Some(options)).await?;
let coll_options = CollectionOptions::builder()
.read_concern(ReadConcern::majority())
.write_concern(WriteConcern::builder().w(Acknowledgment::Majority).build())
.build();
let collection = client
.database("foo")
.collection_with_options("bar", coll_options);
collection
.insert_one_with_session(doc! { "read": "me" }, None, &mut session)
.await?;
collection
.find_one_with_session(doc! { "read": "me" }, None, &mut session)
.await?
.expect("causal consistency guarantees we can read our own writes");
FromStr for ServerAddress (#458)TopologyClosedEvent is the last SDAM event emitted (#485)Debug output of ClientOptions (#512)Clone for Collection<T> even when T isn't Clone (#454)ServerAddress::parse for URI parsing (#471)Collection::clone_with_type (#467) (thanks @PhotonQuantum!)The MongoDB Rust driver team is pleased to announce the 2.0.2 release of the mongodb crate. This release includes a minor bug fix.
The MongoDB Rust driver team is pleased to announce the 2.0.2 release of the mongodb crate. This release includes a minor bug fix.
pub fields from Debug output of ClientOptions (#516)The MongoDB Rust driver team is pleased to announce the 2.0.1 release of the mongodb crate. This release includes a number of bug fixes:
The MongoDB Rust driver team is pleased to announce the 2.0.1 release of the mongodb crate. This release includes a number of bug fixes:
TopologyClosedEvent is the last SDAM event emitted (#485)The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release N…
The MongoDB Rust driver team is pleased to announce the v2.0.0 release of the mongodb crate. This release is the culmination of several months of work, and it contains a number of new features, API improvements, and bug fixes. It is intended that this release will be very stable and that mongodb will not have another major release for quite a long time.
Note that the new minimum supported Rust version (MSRV) is now 1.48.0.
The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release Notes section below.
tokio to v1.x (RUST-633)The async runtime crate tokio reached 1.0, and the driver's dependency on it was updated to 1.0 accordingly. This is a breaking change, since the driver will no longer work with earlier versions of tokio.
bson to v2.0.0 (RUST-1006)The exported version of bson was updated to v2.0.0, which includes its own set of breaking changes. Check out the bson release notes for more information.
This release adds driver support for transactions, which are supported on replica sets in MongoDB 4.0+ and on sharded clusters in MongoDB 4.2+. Transactions require the use of a ClientSession. Each operation in the transaction must pass the ClientSession into it via the _with_session suffixed version of the operation. For more information and detailed examples, see the ClientSession documentation.
use mongodb::options::{Acknowledgment, ReadConcern, TransactionOptions};
use mongodb::{
bson::{doc, Document},
options::WriteConcern,
};
let mut session = client.start_session(None).await?;
let txn_options = TransactionOptions::builder()
.write_concern(WriteConcern::builder().w(Acknowledgment::Majority).build())
.read_concern(ReadConcern::majority())
.build();
session.start_transaction(txn_options).await?;
collection
.insert_one_with_session(doc! { "x": 1 }, None, &mut session)
.await?;
collection
.delete_one_with_session(doc! { "x": 2 }, None, &mut session)
.await?;
session.commit_transaction().await?;
The "snapshot" read concern level was also introduced as part of this feature.
Document as the default generic type for Collection and Cursor (RUST-735)The generic parameter must now always be explicitly specified when referring to these types. Additionally, the Database::collection and Database::collection_with_options helpers now require a generic parameter to be specified as well. This was done to ease and promote the use of serde with the driver. As part of this, Database::collection_with_type was removed as it was no longer necessary.
// old
let collection = db.collection("foo");
let typed_collection = db.collection_with_type::<MySerdeType>("foo");
struct C { cursor: Cursor }
struct Tc { cursor: Cursor<MySerdeType> }
// new
let collection = db.collection::<Document>("foo");
let typed_collection = db.collection::<MySerdeType>("foo");
struct C { cursor: Cursor<Document> }
struct Tc { cursor: Cursor<MySerdeType> }
The driver was updated to leverage the new raw BSON serialization / deserialization functionality introduced in version 2.0.0 of the bson crate, significantly improving the performance of reads and inserts (RUST-870, RUST-871). Additionally, many redundant clones were eliminated (RUST-536) and writes and reads to sockets are now buffered, yielding further performance improvements. Initial benchmarks indicate that large inserts and reads could execute in half the time or less in 2.0.0 than in 1.2.3.
The driver now exposes an API for creating, listing, and deleting indexes.
e.g.
let new_index = IndexModel::builder()
.keys(doc! { "x": 1 })
.options(IndexOptions::builder().unique(true).build())
.build();
let index_name = collection.create_index(new_index, None).await?.index_name;
let index_names = collection.list_index_names().await?;
assert!(index_names.contains(&index_name));
collection.drop_indexes(None).await?;
let index_names = collection.list_index_names().await?;
assert!(!index_names.contains(&index_name));
MongoDB 5.0 introduced the Versioned API, and this release includes support for specifying it via the ClientOptions.
max_pool_size to 10 (RUST-823)In prior versions of the driver, the default max_pool_size was 100, but this is likely far too high to be a default. For some background on the motivation, see here and here. Note that this is also in line with the defaults for r2d2 and bb8.
There is a community-maintained list of API guidelines that every stable Rust library is recommended to meet. The driver's current API wasn't conforming to these guidelines exactly, so a number of improvements were made to ensure that it does. Here we highlight a few of the more important changes made in this effort.
Several improvements were made to the ErrorKind enum according to the guidelines to provide a more consistent and stable API:
Error suffix from each variant nameThe total list of breaking changes is as follows:
ErrorKind::ServerSelectionError => ErrorKind::ServerSelection)ErrorKind::ArgumentError => ErrorKind::InvalidArgument
ErrorKind::InvalidHostname => removed, consolidated into ErrorKind::InvalidArgumentErrorKind::BsonDecode => ErrorKind::BsonDeserializationErrorKind::BsonEncode => ErrorKind::BsonSerializationErrorKind::ResponseError => ErrorKind::InvalidResponseErrorKind::DnsResolve(trust_dns_resolver::error::ResolveError) => ErrorKind::DnsResolve { message: String }
ErrorKind::InvalidDnsName => removed, consolidated into ErrorKind::DnsResolveErrorKind::NoDnsResults => removed, consolidated into ErrorKind::DnsResolveErrorKind::SrvLookupError => removed, consolidated into ErrorKind::DnsResolveErrorKind::TxtLookupError => removed, consolidated into ErrorKind::DnsResolveErrorKind::RustlsConfig(rustls::TLSerror) => ErrorKind::InvalidTlsConfig { message: String }
ErrorKind::ParseError => removed, consolidated into ErrorKind::InvalidTlsConfigErrorKind::WaitQueueTimeoutError => removed, the wait_queue_timeout option is no longer supported (RUST-757)ErrorKind::OperationError => removed, consolidated into ErrorKind::InvalidResponse and ErrorKind::Internal as appropriateThe driver included types from a number of unstable (pre-1.0) dependencies in its public API, which presented a problem for the stability of the driver itself. tokio was one such example of this, which is why when it went 1.0, the driver needed a 2.0 release. In an effort to ensure that the driver will no longer be subject to the semver breaks of unstable dependencies and can stay on 2.0 for the foreseeable future, the public dependencies on unstable types were removed altogether or stabilized such that they will always be present.
Here are the notable changes made as part of that:
Stream trait from futures-core rather than futures.
futures-core will be moving directly to 1.0 next, whereas futures may have several semver-incompatible versions.futures-core 0.3 (current release), even after futures-core 1.0 is released and/or the Stream trait is included in the standard library. The cursor types will also implement each of the Stream traits from futures-core 1.0 and std as necessary, and users can depend on and import the one they wish to use.std::Stream. See (https://github.com/rust-lang/futures-rs/issues/2362)ErrorKind variants that wrapped unstable errors were removed or refactored (see above)ResolverConfig type that opaquely wraps a trust_dns_resolver::ResolverConfigTlsOptions::into_rustls_config was removed from the public APIError::kind in a Box (RUST-742)As an ergonomic improvement to the Error type, the ErrorKind field of Error was updated to be wrapped in a Box instead of an Arc. This will allow you to get an owned ErrorKind via the * operator, which was previously impossible with the Arc wrapper.
impl Borrow<T> in various CRUD methods (RUST-754)Prior to this release, methods such as Collection::insert_one accepted an owned T despite not actually requiring ownership of the value. This could lead to wasteful clones that hurt performance. As an improvement, these methods were updated to accept impl Borrow<T>, which means either owned or borrowed types may be passed in.
Deserialize from Client::list_databases and Database::list_collections (RUST-740)These methods used to return Vec<Document> and Cursor<Document> respectively, both of which do not take advantage of the fact that the format of the returned documents is known and stable. To improve on that, these methods were updated to return Vec<DatabaseSpecification> and Cursor<CollectionSpecification> instead, which should make the responses more ergonomic to work with.
StreamAddress (RUST-760)StreamAddress was used to specify via the ClientOptions which hosts the driver was to connect to. This type was inaccurate though, since it usually contained DNS names that get resolved to one or more socket addresses rather than the socket address itself. Furthermore, in the future the driver may want to support other ways of connecting to MongoDB servers, such as Unix Domain Sockets, which would further make the StreamAddress name confusing. To improve the accuracy of the type's name enable it to be more easily extended in the future, it was refactored to the following type:
#[non_exhaustive]
pub enum ServerAddress {
Tcp { host: String, port: Option<u16> }
}
This is similar to the equivalent types provided by the tokio-postgres and redis crates.
Note: this change only affects users that construct their own ClientOptions structs (as opposed to parsing them from a connection string) or consumers of CMAP events.
Collection to implementation blocks (RUST-852)In prior releases, the generic type T on Collection had a few trait bounds (e.g. DeserializeOwned and Serialize). These bounds could become cumbersome in certain situations where only a subset of them was required, such as when performing a find with a projection (i.e. a read-only type only needs to implement DeserializeOwned). To resolve this issue, the trait bounds were moved from Collection itself to the implementation blocks for the methods that require them, so the T only needs to implement the trait requirements for the methods it's used in.
For example, if a collection is only used for insertion, T only needs to implement Serialize:
#[derive(Debug, Serialize)]
struct Foo {
name: String,
}
// wouldn't compile before because Foo isn't DeserializeOwned, but now compiles because `T` has no trait bounds
let collection = db.collection::<Foo>("foo");
// compiles because Foo is Serialize
collection.insert_one(Foo { name: "Foo".to_string() }, None).await?;
// doesn't compile since Foo isn't DeserializeOwned
collection.find_one(doc! {}, None).await?;
This also has the added benefit of allowing other structs and enums to contain Collection<T> without also having to inherit the trait bounds, as Collection<T> no longer has any.
The driver now exposes an API for monitoring Server Discover and Monitoring events (SDAM), which can be useful when debugging connectivity issues with the driver.
e.g.
struct FailedHeartbeatLogger;
impl SdamEventHandler for FailedHeartbeatLogger {
fn handle_server_heartbeat_failed_event(&self, event: ServerHeartbeatFailedEvent) {
eprintln!("Failed server heartbeat: {:?}", event);
}
}
let handler: Arc<dyn SdamEventHandler> = Arc::new(FailedHeartbeatLogger);
let options = ClientOptions::builder()
.sdam_event_handler(handler)
.build();
let client = Client::with_options(options)?;
// Do things with the client, and failed server heartbeats will be logged to stderr.
bson to 2.0.0 (breaking)Snapshot variant to ReadConcernLevel enumCollection<T> (breaking)tokio to v1.x (breaking)aws-auth feature flag (breaking)getMore and transaction-continuing commands. (#397)HashMap::contains in Error::contains_label (#386)typed-builder to 0.9.0Error and ErrorKind (breaking)StreamAddress to ServerAddress enum (breaking)wait_queue_timeout (breaking)CreateCollectionOptions::validation to CreateCollectionOptions::validator (breaking)WriteConcern::validate as pub(crate) (breaking)impl AsRef<str> instead of &str (breaking)PathBuf instead of String for paths in options (breaking)chrono and uuid interop in bsonmax_pool_size to 10 (breaking)Error::labels (breaking)semver to 1.0 (thanks @dtolnay!)ServerType variants (breaking)err-derive to thiserrorestimated_document_count() to use the $collStats aggregation stageDebug for CredentialConnectionPoolOptions included in events (breaking)hmac 0.11 (thanks @seanpianka!)deletes array for command, not in top-level documentfind methodbackgroundThreadIntervalMS to fix a race condition. (#396)This is the fourth beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, API improvements, and bug fixes t…
The MongoDB Rust driver team is pleased to announce the v2.0.0-beta.3 release of the mongodb crate. This is the fourth beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, API improvements, and bug fixes that were not included in the previous betas. As with the previous betas, we do not intend to make any further breaking changes before v2.0.0, but we may do so in another beta if any issues arise before then.
The following sections detail some of the more important changes included in this release. For a full list of changes, see the Full Release Notes section.
bson to v2.0.0-beta.3The exported version of bson was updated to v2.0.0-beta.3, which includes its own set of changes. Check out the bson release notes for more information.
Support for replica set transactions was introduced in a previous release, and this release expands that support to include sharded clusters! Note that sharded transactions are only supported in MongoDB 4.2+.
The driver was updated to leverage the new raw BSON serialization / deserialization functionality introduced in version 2.0.0-beta.3 of the bson crate, significantly improving the performance of reads and inserts. Initial (rough) benchmarks indicate that large inserts and reads could execute in half the time (or less) than they used to.
Note that as part of this, the generic bound on Collection is now required to be Sync and Send.
MongoDB 5.0 introduced the Versioned API, and this release includes support for specifying it via the ClientOptions.
bson dependency to 2.0.0-beta.3getMore and transaction-continuing commands. (#397)HashMap::contains in Error::contains_label (#386)backgroundThreadIntervalMS to fix a race condition. (#396)This is the third beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, API improvements, and bug fixes th…
The MongoDB Rust driver team is pleased to announce the v2.0.0-beta.2 release of the mongodb crate. This is the third beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, API improvements, and bug fixes that were not included in the first two betas. As with the previous betas, we do not intend to make any further breaking changes before v2.0.0, but we may do so in another beta if any issues arise before then.
The following sections detail some of the more important changes included in this release. For a full list of changes, see the Full Release Notes section.
bson to v2.0.0-beta.2The exported version of bson was updated to v2.0.0-beta.2, which includes its own set of changes. Check out the bson release notes for more information.
Option to builder methods (RUST-858)In a previous release, the builder methods were updated to accept non-Option types, which came with a few ergonomic benefits. Unfortunately, this update made it difficult to pass in Options when needed. After receiving some feedback on this change from beta users, we decided to revert the builders back to the 1.x driver behavior, namely that the builder methods will now take Into<T>, regardless of whether T is an Option or not.
Collection (RUST-851)In a previous release, the Database::collection methods and Cursor types were updated to no longer have Document as their default generic types. It was intended that Collection would be updated in the same manner, but the changes for it were accidentally omitted. This release fixes that, updating Collection to no longer have a default generic type, meaning the generic type of Collection must now always be specified.
A number of unnecessary clones of input documents and command responses were removed from the driver's operation execution logic, leading to significant performance improvements in certain situations. This is part of an ongoing effort to improve the driver's performance, with more changes to come in future releases.
Collection to implementation blocks (RUST-852)In prior releases, the generic type T on Collection had a few trait bounds (e.g. DeserializeOwned and Serialize). These bounds could become cumbersome in certain situations where only a subset of them was required, such as when performing a find with a projection (i.e. a read-only type only needs to implement DeserializeOwned). To resolve this issue, the trait bounds were moved from Collection itself to the implementation blocks for the methods that require them, so the T only needs to implement the trait requirements for the methods it's used in.
For example, if a collection is only used for insertion, T only needs to implement Serialize:
#[derive(Debug, Serialize)]
struct Foo {
name: String,
}
// wouldn't compile before because Foo isn't DeserializeOwned, but now compiles because `T` has no trait bounds
let collection = db.collection::<Foo>("foo");
// compiles because Foo is Serialize
collection.insert_one(Foo { name: "Foo".to_string() }, None).await?;
// doesn't compile since Foo isn't DeserializeOwned
collection.find_one(doc! {}, None).await?;
This also has the added benefit of allowing other structs and enums to contain Collection<T> without also having to inherit the trait bounds, as Collection<T> no longer has any.
Collection (breaking)ServerApiVersion variants to V1, V2, etc.This is the second beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, new features, API improvements, a…
The MongoDB Rust driver team is pleased to announce the v2.0.0-beta.1 release of the mongodb crate. This is the second beta release in preparation for the 2.0.0 stable release, and it contains a few breaking changes, new features, API improvements, and bug fixes that were not included in the first beta. As with the previous beta, we do not intend to make any further breaking changes before v2.0.0, but we may do so in another beta if any issues arise before then.
The following sections detail some of the more important changes included in this release. For a full list of changes, see the Full Release Notes section.
bson to v2.0.0-beta.1The exported version of bson was updated to v2.0.0-beta.1, which includes its own set of breaking changes. Check out the bson release notes for more information.
Note: chrono and uuid public API components are now gated behind the "bson/chrono-0_4" and "bson/uuid-0_8" feature flags respectively.
This release adds driver support the for replica set transactions, which are supported in MongoDB 4.0+. Transactions require the use of a ClientSession, which was introduced in a previous release. Each operation in the transaction must pass the ClientSession into it via the _with_session suffixed version of the operation. For more information and detailed examples, see the ClientSession documentation.
use mongodb::options::{Acknowledgment, ReadConcern, TransactionOptions};
use mongodb::{
bson::{doc, Document},
options::WriteConcern,
};
let mut session = client.start_session(None).await?;
let txn_options = TransactionOptions::builder()
.write_concern(WriteConcern::builder().w(Acknowledgment::Majority).build())
.read_concern(ReadConcern::majority())
.build();
session.start_transaction(txn_options).await?;
collection
.insert_one_with_session(doc! { "x": 1 }, None, &mut session)
.await?;
collection
.delete_one_with_session(doc! { "x": 2 }, None, &mut session)
.await?;
session.commit_transaction().await?;
The "snapshot" read concern level was also introduced as part of this feature.
max_pool_size to 10 (RUST-823)In prior versions of the driver, the default max_pool_size was 100, but this is likely far too high to be a default. For some background on the motivation, see here and here. Note that this is also in line with the defaults for r2d2 and bb8.
Snapshot variant to ReadConcernLevel enumchrono and uuid interop in bson (breaking)max_pool_size to 10 (breaking)Error::labels (breaking)semver to 1.0 (thanks @dtolnay!)The MongoDB Rust driver team is pleased to announce the v2.0.0-beta release of the driver. This release contains a number of breaking changes, API imp…
The MongoDB Rust driver team is pleased to announce the v2.0.0-beta release of the driver. This release contains a number of breaking changes, API improvements, new features, and bug fixes. We do not intend to make any further breaking changes before the v2.0.0 stable release, though we may do so if needed.
The following sections detail some of the more important breaking changes included in this release. For a full list of changes, see the Full Release Notes section.
bson to v2.0.0-betaThe exported version of bson was updated to v2.0.0-beta, which includes its own set of breaking changes. Check out the bson release notes for more information.
There is a community-maintained list of API guidelines that every stable Rust library is recommended to meet. The driver's current API wasn't conforming to these guidelines exactly, so a number of improvements were made to ensure that it does. Here we highlight a few of the more important changes made in this effort.
Several improvements were made to the ErrorKind enum according to the guidelines to provide a more consistent and stable API:
Error suffix from each variant nameThe total list of breaking changes is as follows:
ErrorKind::ServerSelectionError => ErrorKind::ServerSelection)ErrorKind::ArgumentError => ErrorKind::InvalidArgument
ErrorKind::InvalidHostname => removed, consolidated into ErrorKind::InvalidArgumentErrorKind::BsonDecode => ErrorKind::BsonDeserializationErrorKind::BsonEncode => ErrorKind::BsonSerializationErrorKind::ResponseError => ErrorKind::InvalidResponseErrorKind::DnsResolve(trust_dns_resolver::error::ResolveError) => ErrorKind::DnsResolve { message: String }
ErrorKind::InvalidDnsName => removed, consolidated into ErrorKind::DnsResolveErrorKind::NoDnsResults => removed, consolidated into ErrorKind::DnsResolveErrorKind::SrvLookupError => removed, consolidated into ErrorKind::DnsResolveErrorKind::TxtLookupError => removed, consolidated into ErrorKind::DnsResolveErrorKind::RustlsConfig(rustls::TLSerror) => ErrorKind::InvalidTlsConfig { message: String }
ErrorKind::ParseError => removed, consolidated into ErrorKind::InvalidTlsConfigErrorKind::WaitQueueTimeoutError => removed, the wait_queue_timeout option is no longer supported (RUST-757)ErrorKind::OperationError => removed, consolidated into ErrorKind::InvalidResponse and ErrorKind::Internal as appropriateThe driver included types from a number of unstable (pre-1.0) dependencies in its public API, which presented a problem for the stability of the driver itself. tokio was one such example of this, which is why when it went 1.0, the driver needed a 2.0 release. In an effort to ensure that the driver will no longer be subject to the semver breaks of unstable dependencies and can stay on 2.0 for the foreseeable future, the public dependencies on unstable types were removed altogether or stabilized such that they will always be present.
Here are the notable changes made as part of that:
Stream trait from futures-core rather than futures.
futures-core will be moving directly to 1.0 next, whereas futures may have several semver-incompatible versions.futures-core 0.3 (current release), even after futures-core 1.0 is released and/or the Stream trait is included in the standard library. The cursor types will also implement each of the Stream traits from futures-core 1.0 and std as necessary, and users can depend on and import the one they wish to use.std::Stream. See (https://github.com/rust-lang/futures-rs/issues/2362)ErrorKind variants that wrapped unstable errors were removed or refactored (see above)ResolverConfig type that opaquely wraps a trust_dns_resolver::ResolverConfigTlsOptions::into_rustls_config was removed from the public APIError::kind in a Box (RUST-742)In v2.0.0-alpha.1, we removed the Arc wrapper around Error::kind in order to improve the ergonomics of our Error type. The ErrorKind enum is quite large, however, which in turn made Error and mongodb::error::Result large too. In order to balance the ergonomics improvements of having an owned Error::kind with the small size of an Arc wrapped Error::kind, we decided to wrap it in a Box. This reduces the size of Error greatly while also allowing users to get an owned ErrorKind if they wish via the * operator.
The driver uses the typed-builder crate to generate the builders for its various options structs (e.g. ClientOptions::builder()). In this release, we updated its version to 0.9.0 and with that, introduced the following improvements:
Option<T> fields now accept T instead of impl Into<Option<T>>
impl Into<T>, so fields that were options required the explicit Some(...) to enable type inference on the interior type.T also just accept T, rather than Into<T>, allowing for type inference.build() and repeated setters will now issue improved errors via deprecation warnings. See the typed-builder documentation for more information.// old
let options = ClientOptions::builder()
.hosts(vec![StreamAddress {
hostname: "localhost".to_string(),
port: Some(27017),
}])
.read_concern(Some(ReadConcernLevel::Local.into()))
.build();
// new
let options = ClientOptions::builder()
.hosts(vec![ServerAddress::Tcp {
host: "localhost".to_string(),
port: Some(27017),
}])
.read_concern(ReadConcernLevel::Local.into())
.build();
impl Borrow<T> in various CRUD methods (RUST-754)Prior to this release, methods such as Collection::insert_one accepted an owned T despite not actually requiring ownership of the value. This could lead to wasteful clones that hurt performance. As an improvement, these methods were updated to accept impl Borrow<T>, which means either owned or borrowed types may be passed in.
Deserialize from Client::list_databases and Database::list_collections (RUST-740)These methods used to return Vec<Document> and Cursor<Document> respectively, both of which do not take advantage of the fact that the format of the returned documents is known and stable. To improve on that, these methods were updated to return Vec<DatabaseSpecification> and Cursor<CollectionSpecification> instead, which should make the responses more ergonomic to work with.
StreamAddress (RUST-760)StreamAddress was used to specify via the ClientOptions which hosts the driver was to connect to. This type was inaccurate though, since it usually contains DNS names that get resolved to one or more socket addresses rather than the socket address itself. Furthermore, in the future the driver may want to support other ways of connecting to MongoDB servers, such as Unix Domain Sockets, which would further make the StreamAddress name confusing. To improve the accuracy of the type's name enable it to be more easily extended in the future, it was refactored to the following type:
#[non_exhaustive]
pub enum ServerAddress {
Tcp { host: String, port: Option<u16> }
}
This is similar to the equivalent types provided by the tokio-postgres and redis crates.
Note: this change only affects users that construct their own ClientOptions structs (as opposed to parsing them from a connection string) or consumers of CMAP events.
bson to 2.0.0-beta (breaking)typed-builder to 0.9.0 (breaking)Error and ErrorKind (breaking)StreamAddress to ServerAddress enum (breaking)wait_queue_timeout (breaking)CreateCollectionOptions::validation to CreateCollectionOptions::validator (breaking)impl AsRef<str> instead of &str (breaking)PathBuf instead of String for paths in options (breaking)This is the second alpha release in preparation for the 2.0 version of the driver, and it contains a number of breaking changes, new features, and bug…
The MongoDB Rust driver team is pleased to announce the v2.0.0-alpha.1 release of the driver. This is the second alpha release in preparation for the 2.0 version of the driver, and it contains a number of breaking changes, new features, and bug fixes.
This release also contains all of the changes that were included in v1.2.0 but not in v2.0.0-alpha. Check out the release notes for v1.2.0 for more information.
Note: this release also updates the MSRV to 1.47
Document no longer the default generic type for Collection and Cursor (RUST-735)The generic parameter must now always explicitly specified when referring to these types. Additionally, the Database::collection and Database::collection_with_options helpers now require a generic parameter to be specified as well. This was done to ease and promote the use of serde with the driver. As part of this, Database::collection_with_type was removed as it was no longer necessary.
// old
let collection = db.collection("foo");
let typed_collection = db.collection_with_type::<MySerdeType>("foo");
struct C { cursor: Cursor }
struct Tc { cursor: Cursor<MySerdeType> }
// new
let collection = db.collection::<Document>("foo");
let typed_collection = db.collection::<MySerdeType>("foo");
struct C { cursor: Cursor<Document> }
struct Tc { cursor: Cursor<MySerdeType> }
The error API was updated to allow for easier matching by removing the Arc wrapper around Error::kind. Instead, the Arc was moved into the cases that did not implement Clone.
// old
match e.kind.as_ref() {
ErrorKind::Io(e) => todo!(),
_ => todo!()
}
// new
match e.kind {
ErrorKind::Io(e) => todo!(),
_ => todo!()
}
Collection<T> (breaking)ServerType variants (breaking)err-derive to thiserrorestimated_document_count() to use the $collStats aggregation stagedeletes array for command, not in top-level documentfind methodThe MongoDB Rust driver team is pleased to announce the v2.0.0-alpha release of the driver, with support for tokio 1.x.
The MongoDB Rust driver team is pleased to announce the v2.0.0-alpha release of the driver, with support for tokio 1.x.
This release is an unstable alpha which has the primary goal of introducing official support for tokio 1.x. It currently contains features that are not yet complete, but we wanted to get this release out as soon as possible to enable users to start working with the driver and tokio 1.x. The API is unstable and subject to breakages as we work towards a stable 2.0 release.
The MongoDB Rust driver team is pleased to announce the 1.2.5 release of the mongodb crate. This release includes a bug fix for x509 authentication.
The MongoDB Rust driver team is pleased to announce the 1.2.5 release of the mongodb crate. This release includes a bug fix for x509 authentication.
The MongoDB Rust driver team is pleased to announce the 1.2.4 release of the mongodb crate. This release includes a minor bug fix.
The MongoDB Rust driver team is pleased to announce the 1.2.4 release of the mongodb crate. This release includes a minor bug fix.
pub fields from Debug output of ClientOptions (#516)One column per quarter.