Crate mongodb

source ·
Expand description

§MongoDB Rust Driver

Crates.io docs.rs License

This is the officially supported MongoDB Rust driver, a client side library that can be used to interact with MongoDB deployments in Rust applications. It uses the bson crate for BSON support. The driver contains a fully async API that requires tokio. The driver also has a sync API that may be enabled via feature flags.

For more details, including features, runnable examples, troubleshooting resources, and more, please see the official documentation.

§Installation

§Requirements

  • Rust 1.67+ (See the MSRV policy for more information)
  • MongoDB 4.0+
§Supported Platforms

The driver tests against Linux, MacOS, and Windows in CI.

§Importing

The driver is available on crates.io. To use the driver in your application, simply add it to your project’s Cargo.toml.

[dependencies]
mongodb = "3.1.0"

Version 1 of this crate has reached end of life and will no longer be receiving any updates or bug fixes, so all users are recommended to always depend on the latest 2.x release. See the 2.0.0 release notes for migration information if upgrading from a 1.x version.

§Enabling the sync API

The driver also provides a blocking sync API. To enable this, add the "sync" feature to your Cargo.toml:

[dependencies.mongodb]
version = "3.1.0"
features = ["sync"]

Note: The sync-specific types can be imported from mongodb::sync (e.g. mongodb::sync::Client).

§All Feature Flags

FeatureDescription
dns-resolverEnable DNS resolution to allow mongodb+srv URI handling. Enabled by default.
rustls-tlsUse rustls for TLS connection handling. Enabled by default.
openssl-tlsUse openssl for TLS connection handling.
syncExpose the synchronous API (mongodb::sync).
aws-authEnable support for the MONGODB-AWS authentication mechanism.
zlib-compressionEnable support for compressing messages with zlib.
zstd-compressionEnable support for compressing messages with zstd.
snappy-compressionEnable support for compressing messages with snappy.
in-use-encryption-unstableEnable support for client-side field level encryption and queryable encryption. This API is unstable and may be subject to breaking changes in minor releases.
tracing-unstableEnable support for emitting tracing events. This API is unstable and may be subject to breaking changes in minor releases.
compat-3-0-0Required for future compatibility if default features are disabled.

§Web Framework Examples

§Actix

The driver can be used easily with the Actix web framework by storing a Client in Actix application data. A full example application for using MongoDB with Actix can be found here.

§Rocket

The Rocket web framework provides built-in support for MongoDB via the Rust driver. The documentation for the rocket_db_pools crate contains instructions for using MongoDB with your Rocket application.

§Note on connecting to Atlas deployments

In order to connect to a pre-4.2 Atlas instance that’s M2 or bigger, the openssl-tls feature flag must be enabled. The flag is not required for clusters smaller than M2 or running server versions 4.2 or newer.

§Windows DNS note

On Windows, there is a known issue in the trust-dns-resolver crate, which the driver uses to perform DNS lookups, that causes severe performance degradation in resolvers that use the system configuration. Since the driver uses the system configuration by default, users are recommended to specify an alternate resolver configuration on Windows (e.g. ResolverConfig::cloudflare()) until that issue is resolved. This only has an effect when connecting to deployments using a mongodb+srv connection string.

§Warning about timeouts / cancellation

In async Rust, it is common to implement cancellation and timeouts by dropping a future after a certain period of time instead of polling it to completion. This is how tokio::time::timeout works, for example. However, doing this with futures returned by the driver can leave the driver’s internals in an inconsistent state, which may lead to unpredictable or incorrect behavior (see RUST-937 for more details). As such, it is highly recommended to poll all futures returned from the driver to completion. In order to still use timeout mechanisms like tokio::time::timeout with the driver, one option is to spawn tasks and time out on their JoinHandle futures instead of on the driver’s futures directly. This will ensure the driver’s futures will always be completely polled while also allowing the application to continue in the event of a timeout.

§Bug Reporting / Feature Requests

To file a bug report or submit a feature request, please open a ticket on our Jira project:

  • Create an account and login at jira.mongodb.org
  • Navigate to the RUST project at jira.mongodb.org/browse/RUST
  • Click Create Issue - If the ticket you are filing is a bug report, please include as much detail as possible about the issue and how to reproduce it.

Before filing a ticket, please use the search functionality of Jira to see if a similar issue has already been filed.

§Contributing

We encourage and would happily accept contributions in the form of GitHub pull requests. Before opening one, be sure to run the tests locally; check out the testing section for information on how to do that. Once you open a pull request, your branch will be run against the same testing matrix that we use for our continuous integration system, so it is usually sufficient to only run the integration tests locally against a standalone. Remember to always run the linter tests before opening a pull request.

§Running the tests

§Integration and unit tests

In order to run the tests (which are mostly integration tests), you must have access to a MongoDB deployment. You may specify a MongoDB connection string in the MONGODB_URI environment variable, and the tests will use it to connect to the deployment. If MONGODB_URI is unset, the tests will attempt to connect to a local deployment on port 27017.

Note: The integration tests will clear out the databases/collections they need to use, but they do not clean up after themselves.

To actually run the tests, you can use cargo like you would in any other crate:

cargo test --verbose # runs against localhost:27017
export MONGODB_URI="mongodb://localhost:123"
cargo test --verbose # runs against localhost:123
§Auth tests

The authentication tests will only be included in the test run if certain requirements are met:

  • The deployment must have --auth enabled
  • Credentials must be specified in MONGODB_URI
  • The credentials specified in MONGODB_URI must be valid and have root privileges on the deployment
export MONGODB_URI="mongodb://user:pass@localhost:27017"
cargo test --verbose # auth tests included
§Topology-specific tests

Certain tests will only be run against certain topologies. To ensure that the entire test suite is run, make sure to run the tests separately against standalone, replicated, and sharded deployments.

export MONGODB_URI="mongodb://my-standalone-host:27017" # mongod running on 27017
cargo test --verbose
export MONGODB_URI="mongodb://localhost:27018,localhost:27019,localhost:27020/?replicaSet=repl" # replicaset running on ports 27018, 27019, 27020 with name repl
cargo test --verbose
export MONGODB_URI="mongodb://localhost:27021" # mongos running on 27021
cargo test --verbose
§Run the tests with TLS/SSL

To run the tests with TLS/SSL enabled, you must enable it on the deployment and in MONGODB_URI.

export MONGODB_URI="mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=cert.pem&tlsCAFile=ca.pem"
cargo test --verbose

Note: When you open a pull request, your code will be run against a comprehensive testing matrix, so it is usually not necessary to run the integration tests against all combinations of topology/auth/TLS locally.

§Linter Tests

Our linter tests use the nightly version of rustfmt to verify that the source is formatted properly and the stable version of clippy to statically detect any common mistakes. You can use rustup to install them both:

rustup component add clippy --toolchain stable
rustup component add rustfmt --toolchain nightly

Our linter tests also use rustdoc to verify that all necessary documentation is present and properly formatted. rustdoc is included in the standard Rust distribution.

To run the linter tests, run the check-clippy.sh, check-rustfmt.sh, and check-rustdoc.sh scripts in the .evergreen directory. To run all three, use the check-all.sh script.

bash .evergreen/check-all.sh

§Continuous Integration

Commits to main are run automatically on evergreen.

§Minimum supported Rust version (MSRV) policy

The MSRV for this crate is currently 1.67.0. This will rarely be increased, and if it ever is, it will only happen in a minor or major version release.

§License

This project is licensed under the Apache License 2.0.

This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/).

Re-exports§

Modules§

  • Action builder types.
  • Contains the functionality for change streams.
  • client_encryptionin-use-encryption-unstable
    Support for explicit encryption.
  • Contains the Error and Result types that mongodb uses.
  • Contains the events and functionality for monitoring internal Client behavior.
  • Contains the functionality for GridFS operations.
  • Contains all of the types needed to specify options to MongoDB operations.
  • Contains the types of results returned by CRUD operations.
  • syncsync
    Contains the sync API. This is only available when the sync feature is enabled.

Structs§

  • This is the main entry point for the API. A Client is used to connect to a MongoDB cluster. By default, it will monitor the topology of the cluster, keeping track of any changes, such as servers being added or removed.
  • A MongoDB client session. This struct represents a logical session used for ordering sequential operations. To create a ClientSession, call start_session on a Client.
  • Struct modeling a cluster time reported by the server.
  • Collection is the client-side abstraction of a MongoDB Collection. It can be used to perform collection-level operations such as CRUD operations. A Collection can be obtained through a Database by calling either Database::collection or Database::collection_with_options.
  • A Cursor streams the result of a query. When a query is made, the returned Cursor will contain the first batch of results from the server; the individual results will then be returned as the Cursor is iterated. When the batch is exhausted and if there are more results, the Cursor will fetch the next batch of documents, and so forth until the results are exhausted. Note that because of this batching, additional network I/O may occur on any given call to next. Because of this, a Cursor iterates over Result<T> items rather than simply T items.
  • Database is the client-side abstraction of a MongoDB database. It can be used to perform database-level operations or to obtain handles to specific collections within the database. A Database can only be obtained through a Client by calling either Client::database or Client::database_with_options.
  • Specifies the fields and options for an index. For more information, see the documentation.
  • A struct modeling the canonical name for a collection in MongoDB.
  • Specifies the options for a search index.
  • A description of the most up-to-date information known about a server. Further details can be found in the Server Discovery and Monitoring specification.
  • A SessionCursor is a cursor that was created with a ClientSession that must be iterated using one. To iterate, use SessionCursor::next or retrieve a SessionCursorStream using SessionCursor::stream:
  • A type that implements Stream which can be used to stream the results of a SessionCursor. Returned from SessionCursor::stream.

Enums§

  • Specifies the type of search index.
  • Enum representing the possible types of servers that the driver can connect to.
  • The possible types for a topology.

Type Aliases§