The official MongoDB Rust Driver

Overview

MongoDB Rust Driver

Crates.io docs.rs License

This repository contains 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 supports either tokio (default) or async-std, depending on the feature flags set. The driver also has a sync API that may be enabled via feature flag.

Index

Installation

Requirements

Driver Version Required Rust Version
master 1.45+
2.0.0-alpha 1.45+
1.2.x 1.43+
1.1.x 1.43+
1.0.x 1.43+
0.11.x 1.43+
0.10.x 1.43+
0.9.x 1.39+
  • MongoDB 3.6+

Note: A bug affecting Rust 1.46-1.47 may cause out-of-memory errors when compiling an application that uses the 1.1 version of the driver with a framework like actix-web. Upgrading Rust to 1.48+ or the driver to 1.2+ fixes this issue. For more information, see https://github.com/rust-lang/rust/issues/75992.

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 = "1.1.1"

Configuring the async runtime

The driver supports both of the most popular async runtime crates, namely tokio and async-std. By default, the driver will use tokio, but you can explicitly choose a runtime by specifying one of "tokio-runtime" or "async-std-runtime" feature flags in your Cargo.toml.

For example, to instruct the driver to work with async-std, add the following to your Cargo.toml:

[dependencies.mongodb]
version = "1.1.1"
default-features = false
features = ["async-std-runtime"]

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 = "1.1.1"
default-features = false
features = ["sync"]

Note: if the sync API is enabled, the async-specific types will be privatized (e.g. mongodb::Client). The sync-specific types can be imported from mongodb::sync (e.g. mongodb::sync::Client).

Example Usage

Below are simple examples of using the driver. For more specific examples and the API reference, see the driver's docs.rs page.

Using the async API

Connecting to a MongoDB deployment

use mongodb::{Client, options::ClientOptions};
// Parse a connection string into an options struct.
let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?;

// Manually set an option.
client_options.app_name = Some("My App".to_string());

// Get a handle to the deployment.
let client = Client::with_options(client_options)?;

// List the names of the databases in that deployment.
for db_name in client.list_database_names(None, None).await? {
    println!("{}", db_name);
}

Getting a handle to a database

// Get a handle to a database.
let db = client.database("mydb");

// List the names of the collections in that database.
for collection_name in db.list_collection_names(None).await? {
    println!("{}", collection_name);
}

Inserting documents into a collection

use mongodb::bson::doc;
// Get a handle to a collection in the database.
let collection = db.collection("books");

let docs = vec![
    doc! { "title": "1984", "author": "George Orwell" },
    doc! { "title": "Animal Farm", "author": "George Orwell" },
    doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
];

// Insert some documents into the "mydb.books" collection.
collection.insert_many(docs, None).await?;

Finding documents in a collection

use futures::stream::StreamExt;
use mongodb::{
    bson::{doc, Bson},
    options::FindOptions,
};
// Query the documents in the collection with a filter and an option.
let filter = doc! { "author": "George Orwell" };
let find_options = FindOptions::builder().sort(doc! { "title": 1 }).build();
let mut cursor = collection.find(filter, find_options).await?;

// Iterate over the results of the cursor.
while let Some(result) = cursor.next().await {
    match result {
        Ok(document) => {
            if let Some(title) = document.get("title").and_then(Bson::as_str) {
                println!("title: {}", title);
            }  else {
                println!("no title found");
            }
        }
        Err(e) => return Err(e.into()),
    }
}

Using the sync API

The driver also provides a blocking sync API. See the Installation section for instructions on how to enable it.

The various sync-specific types are found in the mongodb::sync submodule rather than in the crate's top level like in the async API. The sync API calls through to the async API internally though, so it looks and behaves similarly to it.

use mongodb::{
    bson::{doc, Bson},
    sync::Client,
};
let client = Client::with_uri_str("mongodb://localhost:27017")?;
let database = client.database("mydb");
let collection = database.collection("books");

let docs = vec![
    doc! { "title": "1984", "author": "George Orwell" },
    doc! { "title": "Animal Farm", "author": "George Orwell" },
    doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
];

// Insert some documents into the "mydb.books" collection.
collection.insert_many(docs, None)?;

let cursor = collection.find(doc! { "author": "George Orwell" }, None)?;
for result in cursor {
    match result {
        Ok(document) => {
            if let Some(title) = document.get("title").and_then(Bson::as_str) {
                println!("title: {}", title);
            } else {
                println!("no title found");
            }
        }
        Err(e) => return Err(e.into()),
    }
}

Platforms

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

Atlas note

Currently, the driver has issues connecting to Atlas tiers above M2 unless the server version is at least 4.2. We're working on fixing this, but in the meantime, a workaround is to upgrade your cluster to 4.2. The driver has no known issues with either M0 or M2 instances.

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 until that issue is resolved. This only has an effect when connecting to deployments using a mongodb+srv connection string.

e.g.

let options = ClientOptions::parse_with_resolver_config(
    "mongodb+srv://my.host.com",
    ResolverConfig::cloudflare(),
)
.await?;
let client = Client::with_options(options)?;

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:20717" # mongod running on 27017
cargo test --verbose
export MONGODB_URI="mongodb://localhost:27018,localhost:27019,localhost:27020/?replSet=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:

bash .evergreen/check-clippy.sh && bash .evergreen/check-rustfmt.sh && bash .evergreen/check-rustdoc.sh

Continuous Integration

Commits to master are run automatically on evergreen.

License

This project is licensed under the Apache License 2.0.

Comments
  • BSON performance

    BSON performance

    Hello Everyone! My team is currently writing a very traffic-heavy server, so our main goals are performance and security (which are Rust's lead perks). I was extremely happy with Rust's actix-web framework performance, before introducing Bson objects. I've started reading about this issue and found those benchmarks, and also an alternative for document operations. https://github.com/only-cliches/NoProto I'm wondering if it's possible to replace BSON with NoProto Documents? They seem to have the same functionality, but noProto is around 160x faster for decodes, and 85x faster for updates of a single document.

    I understand that Document functionality is one of the core MongoDB features, but using BSON for it is a major performance hit for the Rust driver. Changing it might raise the performance several times!

    Thanks for your time and attention!

    My bench results:

    ========= SIZE BENCHMARK =========
    NoProto:     size: 308b, zlib: 198b
    Flatbuffers: size: 264b, zlib: 181b
    Bincode:     size: 163b, zlib: 129b
    Postcard:    size: 128b, zlib: 119b
    Protobuf:    size: 154b, zlib: 141b
    MessagePack: size: 311b, zlib: 193b
    JSON:        size: 439b, zlib: 184b
    BSON:        size: 414b, zlib: 216b
    Prost:       size: 154b, zlib: 142b
    Avro:        size: 702b, zlib: 333b
    Flexbuffers: size: 490b, zlib: 309b
    Abomonation: size: 261b, zlib: 165b
    Rkyv:        size: 180b, zlib: 152b
    Raw BSON:    size: 414b, zlib: 216b
    MessagePack: size: 296b, zlib: 187b
    Serde JSON:  size: 446b, zlib: 198b
    
    ======== ENCODE BENCHMARK ========
    NoProto:           739 ops/ms 1.00
    Flatbuffers:      2710 ops/ms 3.66
    Bincode:          9615 ops/ms 13.03
    Postcard:         4505 ops/ms 6.10
    Protobuf:         1484 ops/ms 2.01
    MessagePack:       760 ops/ms 1.03
    JSON:              700 ops/ms 0.95
    BSON:              196 ops/ms 0.27
    Prost:            1773 ops/ms 2.40
    Avro:              235 ops/ms 0.32
    Flexbuffers:       483 ops/ms 0.65
    Abomonation:      5405 ops/ms 7.30
    Rkyv:             3690 ops/ms 4.99
    Raw BSON:          203 ops/ms 0.28
    MessagePack:       284 ops/ms 0.39
    Serde JSON:       1167 ops/ms 1.58
    
    ======== DECODE BENCHMARK ========
    NoProto:          1085 ops/ms 1.00
    Flatbuffers:     12821 ops/ms 11.81
    Bincode:          6944 ops/ms 6.40
    Postcard:         5682 ops/ms 5.22
    Protobuf:         1727 ops/ms 1.59
    MessagePack:       561 ops/ms 0.52
    JSON:              564 ops/ms 0.52
    BSON:              164 ops/ms 0.15
    Prost:            2625 ops/ms 2.41
    Avro:               72 ops/ms 0.07
    Flexbuffers:       562 ops/ms 0.52
    Abomonation:     83333 ops/ms 73.77
    Rkyv:            58824 ops/ms 52.62
    Raw BSON:          925 ops/ms 0.85
    MessagePack:       376 ops/ms 0.35
    Serde JSON:        377 ops/ms 0.35
    
    ====== DECODE ONE BENCHMARK ======
    NoProto:         30303 ops/ms 1.00
    Flatbuffers:    142857 ops/ms 4.24
    Bincode:          7407 ops/ms 0.24
    Postcard:         6289 ops/ms 0.21
    Protobuf:         1751 ops/ms 0.06
    MessagePack:       721 ops/ms 0.02
    JSON:              714 ops/ms 0.02
    BSON:              186 ops/ms 0.01
    Prost:            2710 ops/ms 0.09
    Avro:               83 ops/ms 0.00
    Flexbuffers:     15385 ops/ms 0.50
    Abomonation:    333333 ops/ms 10.65
    Rkyv:           250000 ops/ms 7.14
    Raw BSON:        15625 ops/ms 0.51
    MessagePack:       404 ops/ms 0.01
    Serde JSON:        375 ops/ms 0.01
    
    ====== UPDATE ONE BENCHMARK ======
    NoProto:         11494 ops/ms 1.00
    Flatbuffers:      2336 ops/ms 0.20
    Bincode:          4367 ops/ms 0.38
    Postcard:         2674 ops/ms 0.23
    Protobuf:          706 ops/ms 0.06
    MessagePack:       312 ops/ms 0.03
    JSON:              525 ops/ms 0.05
    BSON:              136 ops/ms 0.01
    Prost:            1121 ops/ms 0.10
    Avro:               54 ops/ms 0.00
    Flexbuffers:       251 ops/ms 0.02
    Abomonation:      5495 ops/ms 0.48
    Rkyv:             3247 ops/ms 0.28
    Raw BSON:          140 ops/ms 0.01
    MessagePack:       215 ops/ms 0.02
    Serde JSON:        289 ops/ms 0.03
    
    
    //! | Format / Lib                                               | Encode  | Decode All | Decode 1 | Update 1 | Size (bytes) | Size (Zlib) |
    //! |------------------------------------------------------------|---------|------------|----------|----------|--------------|-------------|
    //! | **Runtime Libs**                                           |         |            |          |          |              |             |
    //! | *NoProto*                                                  |         |            |          |          |              |             |
    //! |        [no_proto](https://crates.io/crates/no_proto)       |     739 |       1085 |    30303 |    11494 |          308 |         198 |
    //! | Apache Avro                                                |         |            |          |          |              |             |
    //! |         [avro-rs](https://crates.io/crates/avro-rs)        |     235 |         72 |       83 |       54 |          702 |         333 |
    //! | FlexBuffers                                                |         |            |          |          |              |             |
    //! |     [flexbuffers](https://crates.io/crates/flexbuffers)    |     483 |        562 |    15385 |      251 |          490 |         309 |
    //! | JSON                                                       |         |            |          |          |              |             |
    //! |            [json](https://crates.io/crates/json)           |     700 |        564 |      714 |      525 |          439 |         184 |
    //! |      [serde_json](https://crates.io/crates/serde_json)     |    1167 |        377 |      375 |      289 |          446 |         198 |
    //! | BSON                                                       |         |            |          |          |              |             |
    //! |            [bson](https://crates.io/crates/bson)           |     196 |        164 |      186 |      136 |          414 |         216 |
    //! |         [rawbson](https://crates.io/crates/rawbson)        |     203 |        925 |    15625 |      140 |          414 |         216 |
    //! | MessagePack                                                |         |            |          |          |              |             |
    //! |             [rmp](https://crates.io/crates/rmp)            |     760 |        561 |      721 |      312 |          311 |         193 |
    //! |  [messagepack-rs](https://crates.io/crates/messagepack-rs) |     284 |        376 |      404 |      215 |          296 |         187 |
    //! | **Compiled Libs**                                          |         |            |          |          |              |             |
    //! | Flatbuffers                                                |         |            |          |          |              |             |
    //! |     [flatbuffers](https://crates.io/crates/flatbuffers)    |    2710 |      12821 |   142857 |     2336 |          264 |         181 |
    //! | Bincode                                                    |         |            |          |          |              |             |
    //! |         [bincode](https://crates.io/crates/bincode)        |    9615 |       6944 |     7407 |     4367 |          163 |         129 |
    //! | Postcard                                                   |         |            |          |          |              |             |
    //! |        [postcard](https://crates.io/crates/postcard)       |    4505 |       5682 |     6289 |     2674 |          128 |         119 |
    //! | Protocol Buffers                                           |         |            |          |          |              |             |
    //! |        [protobuf](https://crates.io/crates/protobuf)       |    1484 |       1727 |     1751 |      706 |          154 |         141 |
    //! |           [prost](https://crates.io/crates/prost)          |    1773 |       2625 |     2710 |     1121 |          154 |         142 |
    //! | Abomonation                                                |         |            |          |          |              |             |
    //! |     [abomonation](https://crates.io/crates/abomonation)    |    5405 |      83333 |   333333 |     5495 |          261 |         165 |
    //! | Rkyv                                                       |         |            |          |          |              |             |
    //! |            [rkyv](https://crates.io/crates/rkyv)           |    3690 |      58824 |   250000 |     3247 |          180 |         152 |
    
    opened by xxated 13
  • Cursor iterator returns Error with InvalidResponse

    Cursor iterator returns Error with InvalidResponse "invalid type: unit value, expected a string"

    use mongodb::bson::Document;
    use mongodb::{bson::doc, sync::Client};
    use serde::{Deserialize, Serialize};
    use serde_json::Value;
    
    #[derive(Debug, Serialize, Deserialize)]
    struct ASNEntry {
        asn: i32,
        mode: String,
        name: String,
        description: String,
        prefixes: Vec<PrefixEntry>,
    }
    
    #[derive(Debug, Serialize, Deserialize)]
    struct PrefixEntry {
        prefix: String,
        name: String,
        countryCode: Option<String>,
        description: String,
    }
    
    fn main() {
        let client = Client::with_uri_str("mongodb://mongodb.intern.ninjahub.net:27017").unwrap();
        let database = client.database("censored");
        let collection = database.collection::<ASNEntry>("censored");
        let cursor = collection.find(doc! {}, None).unwrap();
        for result in cursor {
            dbg!(result);
        }
    }
    

    When using the integrated deserialization feature the 102nd Document returns this:

    [src/main.rs:29] result = Err(
        Error {
            kind: InvalidResponse {
                message: "invalid type: unit value, expected a string",
            },
            labels: {},
        },
    )
    [src/main.rs:29] result = Err(
        Error {
            kind: Command(
                CommandError {
                    code: 43,
                    code_name: "CursorNotFound",
                    message: "cursor id 7287796362393293625 not found",
                },
            ),
            labels: {},
        },
    )
    
    
    waiting-for-reporter Stale 
    opened by belohnung 13
  • Can't connect to a mongo cluster(by IPs) which address is behind a vpn

    Can't connect to a mongo cluster(by IPs) which address is behind a vpn

    Hi,

    I'm trying to connect to a replica set by IPs which is behind VPN.

        let client = Client::with_uri_str("mongodb://name:[email protected]:27017,xx.xx.xx.xxx:27017,xx.xx.xx.xxx:27017/?tlsallowinvalidcertificates=true&replicaSet=repl-set-name").expect("db client created");
    
        for db_name in client
            .list_database_names(None, None)
            .expect("database names fetched")
        {
            println!("{}", db_name);
        }
    

    I receive the following error:

    Error { kind: ServerSelection { message: "Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: xx.xx.xx.xxx:27017, Type: Unknown, Error: An error occurred during DNS resolution: InvalidDNSNameError }, { Address: xx.xx.xx.xxx:27017, Type: Unknown, Error: An error occurred during DNS resolution: InvalidDNSNameError }, { Address: xx.xx.xx.xxx:27017, Type: Unknown, Error: An error occurred during DNS resolution: InvalidDNSNameError }, ] }" }, labels: {} }
    

    mongo-rust-driver version: 2.0.0 MongoDB version: 3.6.20

    using mongo shell with the following format I can successfully connect(self signed cert is used):

    mongo --sslAllowInvalidHostnames --ssl --authenticationDatabase 'admin' --host repl-set-name/xx.xx.xx.xxx:27017,xx.xx.xx.xxx:27017,xx.xx.xx.xxx:27017 -u user -p passwd
    

    What I'm doing wrong?

    opened by kakoc 9
  • Rust 275

    Rust 275

    This PR includes two changes:

    • The first is an update to the SCRAM conversation as defined by: https://github.com/mongodb/specifications/commit/d02b627adbc77bb52ca26465a95ef1e37bb5960a#diff-4ae4e931060899b3147a7255caadd990 which introduces a new top level "options" field to the "saslStart" command.
    • The second is removing the done check in validate which allows this client to authenticate with AWS DocumentDB.

    It should be noted that updating the SCRAM conversation causes a new error to be returned:

    OrderedDocument({"saslStart": I32(1), "mechanism": String("SCRAM-SHA-1"), "payload": BinData(0, <redacted, is this sensitive?>), "options": Document(OrderedDocument({"skipEmptyExchange": Boolean(true)}))})

    opened by anthonyjchriste 9
  • RUST-556 POC of maxConnecting

    RUST-556 POC of maxConnecting

    RUST-556

    This PR implements a POC of the maxConnecting requirement of the "Avoiding Connection Storms" project. In doing so, it also re-architects the connection pool to use a channel based WaitQueue rather than semaphore based one. This was done to allow for easier and more effective maintenance of the wait queue now that we need to support arbitrary conditions for exiting the queue (e.g. maxConnecting).

    I realize that a rewrite of this magnitude typically goes through a design phase, so I apologize for suddenly dropping it like this. I decided it was the preferable choice for this POC largely because a counting semaphore wait queue was frustrating to extend to use in this case, and that this lockless + channel-based pattern is a much more common aproach in the async world for accessing shared state than our previous lock heavy one. Maintaining the old pool and adding support for maxConnecting would introduce even more locking while also producing a suboptimal solution (impossible or difficult to ensure fairness with multiple semaphores/locks in this case), so this seemed like an good time for a rewrite. Additionally, this is a proof-of-concept after all, so I figured it would be a good time to proof-of-concept what an idiomatic async pool would look like too. I think that I should have opted for a pool like this back when I originally converted the old pool to async, but I was lacking in experience with async patterns at the time. Ironically, the original sync pool with its queue of condvars was somewhat similar to this one.

    Overview of new pool

    I'll give a brief overview of the layout of the new pool here to make digesting the actual code a little easier. We have the same clonable ConnectionPool type as before with the same functionality; however, when we create a new pool, instead of creating a ConnectionPoolInner type that is arc'd and wrapping that, we start a worker task (ConnectionPoolWorker) that opens up a few different channels, and we store senders to those channels (ConnectionRequester, PoolManager) on the ConnectionPool. The worker task is in charge of all changes and access to the connection pool state; to do anything with the pool, a you need to send a request via one of the two senders mentioned before. To check out a connection for example, a thread sends a ConnectionRequest via a ConnectionRequester and waits for the worker to respond. To perform any other pool interactions (e.g. clearing, checking in), a thread uses the PoolManager to send the appropriate requests. The ConnectionRequesters act like strong references to the pool in that they keep the worker alive until they are all dropped, whereas PoolManagers are like weak references and can still be in scope when the worker ceases execution. A ConnectionPool instance holds onto both a ConnectionRequester and a PoolManager, but a Connection for example only holds on to a PoolManager in order to check itself back in. Instead of having a separate background task for ensuring minPoolSize, the worker task just takes care of that.

    In summary:

    • ConnectionPoolInner gone, replaced with a background worker task ConnectionPoolWorker that has exclusive access to pool state
    • ConnectionPoolWorker listens on a few channels for incoming requests, responding to them as necessary
    • Threads can check out connections via ConnectionRequesters. The ConnectionPoolWorker quits once all the requesters are dropped
    • Threads can modify the pool state via PoolManagers. These do not keep the worker running and may no-op if outlive the worker.
    • Connections use PoolManagers to check themselves back in

    Some notes

    Given this architecture, it was trivially easy to introduce maxConnecting: we simply don't poll the ConnectionRequestReceiver when the pool is empty and has too many pending connections. The actual changes required to implement that part are all in the last few commits or so. Additionally, we now have a context which always has exclusive access to the pool state, making it much easier to reason about. Lastly, the drop implementations of the various connection types have been simplified with the removal of ConnectionPoolInner and DroppedConnectionState.

    opened by patrickfreed 8
  • Update trust-dns-* dependencies

    Update trust-dns-* dependencies

    This has the side effect of replacing tokio=0.1 with 0.3, and reducing the number of dependencies being built.

    I'm trying to reduce the number of dependencies on my projects as I'm moving them to async_await syntax. I noticed that trust-dns-resolver is still using tokio=0.1

    opened by nevi-me 8
  • Help with DateTime & Chrono

    Help with DateTime & Chrono

    Hey, I'm using this crate with mongodb and chrono. This is my current code:

        let mut cursor = db.find(doc! {
            "lastUpdate": {
                "$lte": DateTime::from_chrono::<chrono::Utc>(chrono::DateTime::from_utc(chrono::NaiveDateTime::from_timestamp(DateTime::now().to_chrono().timestamp_millis() - 24 * 60 * 60 * 1000, 0), chrono::Utc))
            }
        }, finder).await.unwrap();
    

    It was working fine, until I started getting this error:

    thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: InvalidResponse { message: "expecting DateTime" }, labels: {} }', src\main.rs:114:22
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    

    I'm not exactly sure what's going on. It just appeared out of the blue. Please let me know if you have any ideas.

    waiting-for-reporter Stale 
    opened by Milo123459 7
  • RUST-766 Use `hyper` in place of `reqwest`

    RUST-766 Use `hyper` in place of `reqwest`

    The PR replaces reqwest in favor of hyper::Client. This will also allow upstream libraries and end-users to have a choice in whether to use reqwest or not.

    • Replaces reqwest::Client with hyper::Client
    • Adds serde_json as direct dependencies (They were already dependencies of reqwest)
    tracked-in-jira 
    opened by AsianIntel 7
  • RUST-577 Versioned API implementation

    RUST-577 Versioned API implementation

    This PR drafts necessary changes to accommodate the versioned API. Note that a significant portion of the diff is the unified tests runner, which I squashed in from #249. I plan to keep this PR up to date as that PR progresses.

    Todo list

    • [x] Allow declaring an API version in a language idiomatic matter
    • [x] Submit declared API version fields with every command
    • [x] Figure out where to append Versioned API fields to command
    • [x] Format code according to style guide
    • [x] Verify correct behaviour using spec tests
    • [x] Provide easier way to create ApiVersion

    See below for notes about open issues in the list above.


    Figure out where to append versioned API fields

    I initially planned to append the Versioned API fields in Client::execute_operation_on_connection, but realised that this is only used when running commands that are part of an operation. Other commands, such as isMaster or all authentication commands are not run through this path, which makes this unfeasible. The common code point would be Message::with_command, which will have to receive the declared API version from the connection that the message is being sent on. This has two downsides: instead of only keeping the API version declared on the client, we need to pass it down through connection options. Furthermore, since command monitoring is hooked into Client::execute_operation_on_connection instead of Connection::send_command, we need to manually append Versioned API fields to command documents for command monitoring. I'm not particularly happy about this as I'd like to keep the logic as contained as possible, but with Connection::send_command being used in multiple places I feel that passing the declared API version as part of the command is not feasible. I'm happy about any ideas how to best implement this.

    Format code

    Will be done at the end - please forgive me for visually butchering the language.

    Spec tests

    While the unified test runner POC is being worked on, not all tests may pass. Currently it fails to compare command objects, but I haven't investigated any further aside from making sure that the Versioned API fields appear as expected. Due to this driver not implementing the transaction spec, the transaction tests will be verified using the second POC driver.

    Easier API for ApiVersion

    The API version is currently declared as follows:

    let mut options = ClientOptions::parse_uri(uri, None).await.unwrap();
    options.server_api = ServerApi {
        version: ServerApiVersion::Version1,
        strict: None,
        deprecation_errors: None,
    };
    

    This feels cumbersome, as users are required to pass values for strict and deprecation_errors explicitly, even when they want to rely on the default. A factory would be useful, but I'm not sure what an idiomatic factory in Rust would look like. Following options come to mind:

    // Variant 1: Factory to create ServerApi object from string, set other fields directly:
    let mut server_api = ServerApi::from_string("1");
    server_api.strict = true;
    server_api.deprecation_errors = true;
    
    // Variant 2: Have methods to modify initially created object
    let server_api = ServerApi::from_string("1");
    // Example: enable strict mode and deprecation errors directly
    let server_api = ServerApi::from_string("1").strict(true).deprecation_errors(true);
    
    opened by alcaeus 7
  • How do you close a change stream?

    How do you close a change stream?

    With Node.js, I can do this to start and stop a change stream:

    const changeStream = client.db("database").collection("collection").watch();
    
    changeStream.close();
    

    With Rust, I can get a change stream cursor with this:

    let mut change_stream = client.database("database").collection::<Document>("collection").watch(None, None).await?;
    

    However, I'm very new to Rust and I can't figure out how to close the cursor. Any help would be greatly appreciated!

    opened by Zertz 6
  • Cannot execute query in shared library with existing tokio runtime.

    Cannot execute query in shared library with existing tokio runtime.

    Cannot execute query in shared library with existing tokio runtime.

    Versions/Environment

    1. What version of Rust are you using? rustc 1.62.0 (a8314ef7d 2022-06-27)
    2. What operating system are you using?
      	WindowsBuildLabEx                                       : 19041.1.amd64fre.vb_release.191206-1406
      	WindowsCurrentVersion                                   : 6.3
      	WindowsEditionId                                        : ProfessionalWorkstation
      	WindowsInstallationType                                 : Client
      	WindowsProductId                                        : 00391-70000-00000-AA845
      	WindowsProductName                                      : Windows 10 Pro for Workstations
      
    3. What versions of the driver and its dependencies are you using? (Run cargo pkgid mongodb & cargo pkgid bson)
      	https://github.com/rust-lang/crates.io-index#[email protected]
      	https://github.com/rust-lang/crates.io-index#[email protected]
      
    4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version()) 5.0.9
    5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)? standalone

    Describe the bug

    When I call the mongo api in shared library with existing tokio runtime created by main executable, it shows error like 
    
    thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: ServerSelection { message: "Server selection timeout: No available servers. Topology: { Type: Unknown, Servers: [ { Address: 127.0.0.1:27017, Type: Unknown }, ] }" }, labels: {}, wire_version: None, source: None }', src\lib.rs:67:92
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    
    But when I integrated into the same executable, it seems to be working fine.
    I will upload a test package so that you can reproduce the problem.
    

    BE SPECIFIC:

    • What is the expected behavior and what is actually happening? The expected behavior is to get collection name.

    • Do you have any particular output that demonstrates this problem? At least it should not block the thread, then it should show the collection in my db.

    • Do you have any ideas on why this may be happening that could give us a clue in the right direction? Maybe there are some thread local variables?

    • Did this issue arise out of nowhere, or after an update (of the driver, server, and/or Rust)? Arise out of nowhere

    • Are there multiple ways of triggering this bug (perhaps more than one function produce a crash)? Any query function.

    • If you know how to reproduce this bug, please include a code snippet here:

      See this: mongo-bug-fix

    To Reproduce

    You can see README.md to reproduce the bug.
    
    waiting-for-reporter Stale 
    opened by GhostLee 6
  • Can't filter by ObjectID

    Can't filter by ObjectID

    It is very convenient that the examples provided under usage never filter by _id. Why is it so difficult? It feels like I'm the only one using MongoDB in Rust even though there's 1.2k stars.

    Please let me know which one of these is the right answer.

    let id = "63b4d581231527b4896f36e6";
    let oid = ObjectId::parse_str(&id)?;
    let posts_coll = db.app_db().collection::<BlogPost>("posts");
    posts_coll.find_one(doc!{"_id": &id}, None).await.unwrap()  // 404
    posts_coll.find_one(doc!{"_id": oid}, None).await.unwrap()  // Serialize error
    posts_coll.find_one(doc!{"_id": {"$oid": &id}}, None).await.unwrap()  // unknown operator $set
    posts_coll.find_one(doc!{"_id": oid.to_string()}, None).await.unwrap()  // 404
    

    You might have realized this is too intuitive for developers. Only an unintuitive solutions should work!

    Let's create an entirely new struct just for the sake of filtering by id! What an ingenious solution! Nobel prize status.

    
    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct Id{
        pub _id: ObjectId
    }
    
    posts_coll.find_one(bson::to_document(&Id{_id: oid}).unwrap(), None).await.unwrap()
    

    Nahhhhh same errors

    thread 'rocket-worker-thread' panicked at 'called Result::unwrap() on an Err value: Error { kind: BsonDeserialization(DeserializationError { message: "invalid type: map, expected a string" }), labels: {}, wire_version: None, source: None }', src\blog.rs:59:86

    Maybe we need to change the type of the collection to Document? Nah that doesn't work either!

    Full code

    #[get("/posts/<id>")]
    async fn blog_post(id: String, db: Connection<MainDatabase>) -> Result<Template, Status> {
        let posts_coll = db.app_db().collection::<Document>("posts");
        let oid = ObjectId::parse_str(&id).map_err(|_e| Status::InternalServerError)?;
        print!("{id}");
        match posts_coll.find_one(doc!{"_id": &id}, None).await.unwrap() {
            Some(post) => Ok(Template::render("blog/post", context! {post})),
            _ => Err(Status::NotFound)
        }
    }
    

    posts collection

    {
      "_id": {
        "$oid": "63b4d581231527b4896f36e6"
      },
      "title": "First Post!!!",
      "content": "Hey there, this is some rad content",
      "published": {
        "$date": "2023-01-04T01:25:21.194Z"
      }
    }
    

    63b4d581231527b4896f36e6

    posts_coll.find_one(doc!{"title": "First Post!!!"}, None).await.unwrap()

    works fine

    triage 
    opened by elibroftw 0
  • Querying for a document and getting

    Querying for a document and getting "invalid utf-8 sequence of 1 bytes from index 119" despite not even trying to deserialize anything

    Versions/Environment

    1. What version of Rust are you using? - 1.65.0
    2. What operating system are you using? - WSL (Linux on windows)
    3. What versions of the driver and its dependencies are you using? (Run cargo pkgid mongodb & cargo pkgid bson) - [email protected] & [email protected]
    4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version()) - 5.0.14
    5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)? - Replica Set - 3 nodes

    Describe the bug

    A clear and concise description of what the bug is.

    I am attempting to query for a document that is giving me an error about "invalid utf-8 sequence". I've done a lot of googling on this issue but no luck so far. Nothing related to mongodb :(

    The document is quite large, so that might be a potential issue, but I'm not sure.

    I'm able to query for another document from the same collection without issue, and that document is also quite large, so I'm not sure if the size is the issue.

    I have removed all the properties from the struct so I'm not trying to deserliaze anything at this point, just get the document successfully - and I still get this error. 😢

    My next move is to manually delete much of the data out of the document or query for a different document... but obviously none of this is ideal. I'd just like to get someone to point me in the right direction on what the cause of this error might be.

    Also important to note is I use Mongodb App Services(formerly Realm, formerly Stitch) and I ran schema validations across these documents and everything passes.

    Here's the code, but I don't think it helps much:

    // manually setting ID for the query
    let id = ObjectId::from_str("6116dc1633616dc8924e1050").unwrap();
            let filter_document = doc! {"userId": id};
            let find_one_options = FindOneOptions::builder().build();
            let profile = self
                .profiles_repository
                .find_one::<Profile >(filter_document, find_one_options)
                .await;
    
    //inside find_one
    async fn find_one<'b, T: DeserializeOwned + Sync + Send + Unpin>(
            &self,
            filter: Document,
            find_one_options: FindOneOptions,
        ) -> Result<Option<T>, Error> {
            let collection = self
                .client
                .database("Occasionally")
                .collection::<T>("Profiles");
    
            collection.find_one(filter, find_one_options).await
        }
    
    // Profile Struct, commented out all the props :(
    #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Profile {
        // pub other_id: Option<ObjectId>,
        // pub complex_prop: Vec<OtherStruct>,
        // pub user_id: Option<ObjectId>,
    }
    

    Any help is greatly appreciated and please let me know if I can provide any other information.

    opened by LukasDeco 3
  • RUST-1559 Impl Serialize for WriteFailure, WriteConcernError, WriteError, and BulkWriteFailure

    RUST-1559 Impl Serialize for WriteFailure, WriteConcernError, WriteError, and BulkWriteFailure

    This will very useful for returning detailed errors in JSON format in actix web and co.

    Currently we can't do something like this with KhWriteFailure etc unless Serialize is also implemented for the structures either by using derive_macro! or manually!

    #[derive(Debug, Deserialize, Serialize)]
    pub enum KhoomiResponseError {
        WriteError(WriteFailure),
    }
    
    impl ResponseError for KhoomiResponseError {
        fn status_code(&self) -> StatusCode {
            match self {
                  ...,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            }
        }
    
        fn error_response(&self) -> HttpResponse {
            HttpResponse::build(self.status_code())
                .insert_header(ContentType::html())
                .json(self)
        }
    }
    

    I was able to fix this by creating a custom KhWriteFailure that implements Serialize and then impl From<WriteFailure> for KhWriteFailure

    tracked-in-jira 
    opened by borngraced 0
  • RUST-1545 Consider removing the take_mut dependency

    RUST-1545 Consider removing the take_mut dependency

    Versions/Environment

    1. What version of Rust are you using? Rust 1.65
    2. What operating system are you using? N/A
    3. What versions of the driver and its dependencies are you using? (Run cargo pkgid mongodb & cargo pkgid bson) Driver v2.3.1
    4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version()) N/A
    5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)? N/A

    Describe the bug

    There is a potential memory leak in take_mut, which I noted from 2 issues filed with cargo-crev. A pull request with a fix was opened several years ago and it hasn't been merged yet, so the repository might also be rightly considered abandoned.

    Is this dependency necessary? Something to consider, as it also uses unproven unsafe code.

    https://github.com/yvt/crev-proofs and https://github.com/vorner/crev-proofs both reported issues.

    tracked-in-jira 
    opened by seanpianka 2
  • RUST-1488 Populate inserted_ids when an insert_many fails

    RUST-1488 Populate inserted_ids when an insert_many fails

    fixes #748

    The fix ended up being a little more complicated than I initially expected in order to get it work properly for multi-batch bulk writes but was still relatively straightforward; most of the diff here is just adding testing. @isabelatkinson we should consider adding automated tests around this type of thing as part of the new bulk spec

    opened by kmahar 1
Releases(v2.3.1)
  • v2.3.1(Oct 3, 2022)

    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.

    Full Release Notes

    Bugfixes

    • [RUST-1464] - async-std connection establishment is blocking
    • [RUST-1443] - Monitors do not exit when servers are removed from the topology
    Source code(tar.gz)
    Source code(zip)
  • v2.3.0(Jul 19, 2022)

    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.

    Highlighted Changes

    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.

    MSRV Increase (RUST-1263)

    The minimum supported Rust version (MSRV) for this crate is now Rust 1.53.

    MongoDB 6.0 Support

    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.

    Changes to 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.

    New ConnectionString type

    RUST-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:

    1. 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,
    2. When using a 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.

    Included Tickets

    Below are a selected list of tickets with user impact; for a full list of completed tickets see this Jira query.

    Bug

    • [RUST-332] - Operations don't report errors for invalid setName in single topologies
    • [RUST-1274] - commitTransaction retry sometimes fails with InvalidOptions error
    • [RUST-1328] - ServerDescriptionChangedEvents for servers with errors always emitted even when description does not change
    • [RUST-1337] - Significant performance regression in large reads

    New Feature

    • [RUST-910] - Add server connectionId to command monitoring events
    • [RUST-1070] / [RUST-1145] - Support let option for multiple CRUD commands
    • [RUST-1166] - Change streams support for user-facing PIT pre- and post-images
    • [RUST-1193] - Introduce ConnectionString type
    • [RUST-1215] - Add comment option to EstimatedDocumentCountOptions
    • [RUST-1271] - Clustered Indexes for all Collections
    • [RUST-1290] - Always report wallTime in the change stream event output

    Task

    • [RUST-1263] - Bump MSRV to 1.53
    • [RUST-1311] - Bump maxWireVersion for MongoDB 6.0

    Improvement

    • [RUST-488] - Allow using both async and sync API
    • [RUST-585] - Refactor Topology to use channels instead of locks
    • [RUST-803] - Use "hello" command for monitoring if supported
    • [RUST-1152] - Use hello command + OP_MSG when 'loadBalanced=True'
    • [RUST-1168] - Do not error when parsing change stream event documents
    • [RUST-1216] - Use the count command instead of collStats to implement estimated_document_count
    • [RUST-616] - Raise an error if response messageLength > ismaster.maxMessageSizeBytes
    Source code(tar.gz)
    Source code(zip)
  • v2.3.0-beta(Jun 7, 2022)

    The MongoDB Rust driver team is pleased to announce the v2.3.0-beta release of the mongodb crate.

    Highlighted Changes

    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.

    MSRV Increase (RUST-1263)

    The minimum supported Rust version (MSRV) for this crate is now Rust 1.53.

    MongoDB 6.0 Support

    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.

    Changes to 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.

    New ConnectionString type

    RUST-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:

    1. 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,
    2. When using a 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.

    Included Tickets

    Below are a selected list of tickets with user impact; for a full list of completed tickets see this Jira query.

    Bug

    • [RUST-332] - Operations don't report errors for invalid setName in single topologies
    • [RUST-1274] - commitTransaction retry sometimes fails with InvalidOptions error
    • [RUST-1328] - ServerDescriptionChangedEvents for servers with errors always emitted even when description does not change
    • [RUST-1337] - Significant performance regression in large reads

    New Feature

    • [RUST-1166] - Change streams support for user-facing PIT pre- and post-images
    • [RUST-1193] - Introduce ConnectionString type
    • [RUST-1271] - Clustered Indexes for all Collections
    • [RUST-1290] - Always report 'wallTime' in the change stream event output

    Task

    • [RUST-1263] - Bump MSRV to 1.53
    • [RUST-1311] - Bump maxWireVersion for MongoDB 6.0

    Improvement

    • [RUST-488] - Allow using both async and sync API
    • [RUST-585] - Refactor Topology to use channels instead of locks
    • [RUST-803] - Use "hello" command for monitoring if supported
    • [RUST-1152] - Use hello command + OP_MSG when 'loadBalanced=True'
    • [RUST-1168] - Do not error when parsing change stream event documents
    • [RUST-1216] - Use the count command instead of collStats to implement estimatedDocumentCount
    Source code(tar.gz)
    Source code(zip)
  • v2.2.2(Jun 3, 2022)

    Description

    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.

    Full Release Notes

    Bugfixes

    • RUST-1337 Use tokio's AsyncRead and AsyncWrite traits (#669)
      • This change fixes the performance regression mentioned above.
    • RUST-1274 Fix commitTransaction on checkout retries (#651)
    Source code(tar.gz)
    Source code(zip)
  • v2.2.1(Apr 22, 2022)

    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.

    Included tickets

    • [RUST-1272] - docs.rs failed to build mongodb-2.2.0
    Source code(tar.gz)
    Source code(zip)
  • v2.2.0(Apr 14, 2022)

    Description

    The MongoDB Rust driver team is pleased to announce the v2.2.0 release of the mongodb crate.

    Highlighted Changes

    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.

    Change Streams (RUST-521, RUST-74, RUST-522, RUST-1149, RUST-523, RUST-1104)

    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)}))
    }
    

    Raw BSON Incorporation (RUST-1133, RUST-1175)

    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()?);
    }
    

    MSRV and Dependency Update (RUST-1192, RUST-1220)

    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.

    OpenSSL Support (RUST-1083)

    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.

    Full Release Notes

    New Features

    • RUST-521 Implement naive streaming and resume token caching for change streams (#531)
    • RUST-1133 Update driver to use the raw BSON API (#546)
    • RUST-74 Add cluster_time to ChangeStreamEvent (#548)
    • RUST-522 Implement resume functionality for change streams (#547)
    • RUST-1149 Prose tests for change streams. (#561)
    • RUST-523 Support change streams in unified spec tests (#564)
    • RUST-1104 sync wrapper for the change stream API (#566)
    • RUST-1106 Make the change streams API visible (#571)
    • RUST-43 Add change streams examples for documentation (#572)
    • RUST-1138 Add bson-serde_with feature flag (#580)
    • RUST-1175 Support zero-copy deserialization from cursors (#579)
    • RUST-995 Add tokio-sync feature flag (#578)
    • RUST-1083 Add openssl as an optional TLS provider (#590)

    Bugfixes

    • minor: derive TypedBuilder for TimeseriesOptions (#557)
    • minor: fix external crate links (#552)
    • RUST-1163 Fix load balancer tests (#576)
    • RUST-812 Reduce flakiness of in_window::load_balancing_test (#568)
    • RUST-1163 Fix load balancer auth tests (#581)
    • RUST-1268 Use rustc_version_runtime for runtime metadata (#622)

    Improvements

    • RUST-1088 Always specify error labels at the top level (#553)
    • RUST-894 Unskip write_error::details test on sharded clusters (#526)
    • RUST-395 Log skipped tests (#523)
    • RUST-1143 Bump max wire version to 15 (#573)
    • RUST-1077 Update read/write concern document tests (#567)
    • RUST-1173 Replace "Versioned API" references with "Stable API" (#585)
    • RUST-1192 Bump MSRV to 1.49.0 (#584)
    • RUST-1207 Bump zstd to v0.10 (#588) (thanks @moy2010!)
    • RUST-1220 Bump outdated dependencies (#596)
    • RUST-886 Use lossy UTF-8 decoding for responses to insert and update commands (#601)
    • RUST-803 Conditionally use hello for monitoring (#600)
    • RUST-1064 Retry on handshake failure (#598)
    Source code(tar.gz)
    Source code(zip)
  • v2.2.0-beta(Mar 28, 2022)

    Description

    The MongoDB Rust driver team is pleased to announce the v2.2.0-beta release of the mongodb crate.

    Highlighted Changes

    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.

    Change Streams (RUST-521, RUST-74, RUST-522, RUST-1149, RUST-523, RUST-1104)

    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)}))
    }
    

    Raw BSON Incorporation (RUST-1133, RUST-1175)

    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()?);
    }
    

    MSRV and Dependency Update (RUST-1192, RUST-1220)

    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.

    OpenSSL Support (RUST-1083)

    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.

    Full Release Notes

    New Features

    • RUST-521 Implement naive streaming and resume token caching for change streams (#531)
    • RUST-1133 Update driver to use the raw BSON API (#546)
    • RUST-74 Add cluster_time to ChangeStreamEvent (#548)
    • RUST-522 Implement resume functionality for change streams (#547)
    • RUST-1149 Prose tests for change streams. (#561)
    • RUST-523 Support change streams in unified spec tests (#564)
    • RUST-1104 sync wrapper for the change stream API (#566)
    • RUST-1106 Make the change streams API visible (#571)
    • RUST-43 Add change streams examples for documentation (#572)
    • RUST-1138 Add bson-serde_with feature flag (#580)
    • RUST-1175 Support zero-copy deserialization from cursors (#579)
    • RUST-995 Add tokio-sync feature flag (#578)
    • RUST-1083 Add openssl as an optional TLS provider (#590)

    Bugfixes

    • minor: derive TypedBuilder for TimeseriesOptions (#557)
    • minor: fix external crate links (#552)
    • RUST-1163 Fix load balancer tests (#576)
    • RUST-812 Reduce flakiness of in_window::load_balancing_test (#568)
    • RUST-1163 Fix load balancer auth tests (#581)

    Improvements

    • RUST-1088 Always specify error labels at the top level (#553)
    • RUST-894 Unskip write_error::details test on sharded clusters (#526)
    • RUST-395 Log skipped tests (#523)
    • RUST-1143 Bump max wire version to 15 (#573)
    • RUST-1077 Update read/write concern document tests (#567)
    • RUST-1173 Replace "Versioned API" references with "Stable API" (#585)
    • RUST-1192 Bump MSRV to 1.49.0 (#584)
    • RUST-1207 Bump zstd to v0.10 (#588) (thanks @moy2010!)
    • RUST-1220 Bump outdated dependencies (#596)
    • RUST-886 Use lossy UTF-8 decoding for responses to insert and update commands (#601)
    • RUST-803 Conditionally use hello for monitoring (#600)
    • RUST-1064 Retry on handshake failure (#598)
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Dec 14, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update dependency on bson to v2.1.0

    The 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.

    Support for Atlas Serverless (RUST-653, RUST-983)

    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.

    Wire protocol compression (RUST-54)

    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);
    

    Causal consistency (RUST-48)

    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");
    

    Full Release Notes

    New Features

    • RUST-653 Load Balancer Support (#415, #421, #422, #495, #446, #461, #469, #470, #465, #473, #477, #480, #495, #510)
    • RUST-903 Serverless Testing (#494, #497, #505, #504)
    • RUST-48 Causal consistency support (#493)
    • RUST-54 Add support for reading and writing OP_COMPRESSED (#476)
    • RUST-1048 Expose the default database from Client and ClientOptions (#488) (thanks @WindSoilder!)
    • RUST-892 Implement FromStr for ServerAddress (#458)

    Bugfixes

    • RUST-1122 Fix x509 auth for pkcs8 keys and Atlas free tier (#532) (thanks for reporting @Zageron!)
    • RUST-856 Fix race between server selection and server monitoring (#460)
    • RUST-992 Fix default authSource for PLAIN authentication (#451)
    • RUST-1037 secondaryPreferred read preference is not forwarded to mongos (#480)
    • RUST-1046 Fix iteration of session cursors when batchSize doesn't divide result size (#483)
    • RUST-1047 Ensure TopologyClosedEvent is the last SDAM event emitted (#485)
    • RUST-1060 Omit non-pub fields from Debug output of ClientOptions (#512)

    Improvements

    • RUST-993 Implement Clone for Collection<T> even when T isn't Clone (#454)
    • RUST-949 Use SDAM monitoring in auth_error test
    • RUST-1021 Use ServerAddress::parse for URI parsing (#471)
    • RUST-1032 Avoid redundant allocations in Collection::clone_with_type (#467) (thanks @PhotonQuantum!)
    • RUST-1076 Remove conditional definition of driver modules (#511)
    • RUST-807 Disallow maxPoolSize=0 (#491)
    • RUST-1027 Update maxWireVersion to 14 in support of 5.1 (#503)
    • RUST-1076 Remove conditional module definitions (#511)

    Task

    • RUST-867 Document some performance best practices (#466)
    • RUST-781 Remove unwraps from examples (#474)
    • RUST-536 Aggregation, runCommand, and index management examples (#508)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.5(Dec 14, 2021)

    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.

    • RUST-1122 Fix x509 auth for pkcs8 keys and Atlas free tier (#532) (thanks for reporting @Zageron!)
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0-beta(Nov 16, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update dependency on bson to v2.1.0-beta

    The 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.

    Support for Atlas Serverless (RUST-653, RUST-983)

    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.

    Wire protocol compression (RUST-54)

    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);
    

    Causal consistency (RUST-48)

    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");
    

    Full Release Notes

    New Features

    • RUST-653 Load Balancer Support (#415, #421, #422, #495, #446, #461, #469, #470, #465, #473, #477, #480, #495, #510)
    • RUST-903 Serverless Testing (#494, #497, #505, #504)
    • RUST-48 Causal consistency support (#493)
    • RUST-54 Add support for reading and writing OP_COMPRESSED (#476)
    • RUST-1048 Expose the default database from Client and ClientOptions (#488) (thanks @WindSoilder!)
    • RUST-892 Implement FromStr for ServerAddress (#458)

    Bugfixes

    • RUST-856 Fix race between server selection and server monitoring (#460)
    • RUST-992 Fix default authSource for PLAIN authentication (#451)
    • RUST-1037 secondaryPreferred read preference is not forwarded to mongos (#480)
    • RUST-1046 Fix iteration of session cursors when batchSize doesn't divide result size (#483)
    • RUST-1047 Ensure TopologyClosedEvent is the last SDAM event emitted (#485)
    • RUST-1060 Omit non-pub fields from Debug output of ClientOptions (#512)

    Improvements

    • RUST-993 Implement Clone for Collection<T> even when T isn't Clone (#454)
    • RUST-949 Use SDAM monitoring in auth_error test
    • RUST-1021 Use ServerAddress::parse for URI parsing (#471)
    • RUST-1032 Avoid redundant allocations in Collection::clone_with_type (#467) (thanks @PhotonQuantum!)
    • RUST-1076 Remove conditional definition of driver modules (#511)
    • RUST-807 Disallow maxPoolSize=0 (#491)
    • RUST-1027 Update maxWireVersion to 14 in support of 5.1 (#503)
    • RUST-1076 Remove conditional module definitions (#511)

    Task

    • RUST-867 Document some performance best practices (#466)
    • RUST-781 Remove unwraps from examples (#474)
    • RUST-536 Aggregation, runCommand, and index management examples (#508)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Nov 12, 2021)

    Description

    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.

    • RUST-1060 Omit non-pub fields from Debug output of ClientOptions (#516)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.4(Nov 12, 2021)

    Description

    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.

    • RUST-1060 Omit non-pub fields from Debug output of ClientOptions (#516)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Oct 12, 2021)

    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:

    • RUST-1046 Fix iteration of cursors when batchSize doesn't divide result size (#484, #482)
      • Thanks for reporting @Weakky!
    • RUST-1047 Ensure TopologyClosedEvent is the last SDAM event emitted (#485)
    • RUST-856 Fix race between server selection and server monitoring (#460)
    • RUST-992 Enable auth tests for PLAIN and fix default authSource for such (#451)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Sep 7, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update dependency on 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.

    Update dependency on 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.

    Transactions support (RUST-90)

    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.

    Remove 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> }
    

    Performance Improvements (RUST-518)

    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.

    Index Management API (RUST-273)

    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));
    

    Versioned API support (#401)

    MongoDB 5.0 introduced the Versioned API, and this release includes support for specifying it via the ClientOptions.

    Reduce the default 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.

    Ensure API meets the Rust API Guidelines (RUST-765)

    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.

    Various error API improvements (RUST-739, RUST-765)

    Several improvements were made to the ErrorKind enum according to the guidelines to provide a more consistent and stable API:

    • The variants no longer wrap error types from unstable dependencies (C-STABLE)
    • The variant are named more consistently (C-WORD-ORDER)
      • Drop redundant Error suffix from each variant name
    • Redundant error variants were consolidated

    The total list of breaking changes is as follows:

    • All error variants dropped the "Error" suffix (e.g. ErrorKind::ServerSelectionError => ErrorKind::ServerSelection)
    • ErrorKind::ArgumentError => ErrorKind::InvalidArgument
      • ErrorKind::InvalidHostname => removed, consolidated into ErrorKind::InvalidArgument
    • ErrorKind::BsonDecode => ErrorKind::BsonDeserialization
    • ErrorKind::BsonEncode => ErrorKind::BsonSerialization
    • ErrorKind::ResponseError => ErrorKind::InvalidResponse
    • ErrorKind::DnsResolve(trust_dns_resolver::error::ResolveError) => ErrorKind::DnsResolve { message: String }
      • ErrorKind::InvalidDnsName => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::NoDnsResults => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::SrvLookupError => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::TxtLookupError => removed, consolidated into ErrorKind::DnsResolve
    • ErrorKind::RustlsConfig(rustls::TLSerror) => ErrorKind::InvalidTlsConfig { message: String }
      • ErrorKind::ParseError => removed, consolidated into ErrorKind::InvalidTlsConfig
    • ErrorKind::WaitQueueTimeoutError => removed, the wait_queue_timeout option is no longer supported (RUST-757)
    • ErrorKind::OperationError => removed, consolidated into ErrorKind::InvalidResponse and ErrorKind::Internal as appropriate

    Stabilize or eliminate public dependencies on unstable types (C-STABLE, RUST-739)

    The 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:

    • Cursor types now implement the 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.
      • The 2.0 version of the driver will continue to depend on 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.
      • It's possible no changes will need to be made in the driver to transition to std::Stream. See (https://github.com/rust-lang/futures-rs/issues/2362)
    • ErrorKind variants that wrapped unstable errors were removed or refactored (see above)
    • Introduced a ResolverConfig type that opaquely wraps a trust_dns_resolver::ResolverConfig
    • TlsOptions::into_rustls_config was removed from the public API

    Wrap Error::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.

    Accept 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.

    Return types that implement 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.

    Refactor 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.

    Move trait bounds from 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.

    SDAM Monitoring support (RUST-232)

    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.
    

    Full Release Notes

    New features

    • RUST-1006 Upgrade bson to 2.0.0 (breaking)
    • RUST-90, RUST-734 Implement transactions support
    • RUST-273 Index management API
    • RUST-232 SDAM monitoring API
    • RUST-732 Mark the versioned API options public. (#401)
    • RUST-885 Support snapshot sessions (#390)
    • RUST-666 Add options for timeseries collection creation (#381)
    • RUST-824 Add Snapshot variant to ReadConcernLevel enum
    • RUST-738 Implement Clone on BSON error types (breaking)
    • RUST-740 Return Deserialize types from list_databases and list_collections (breaking)
    • RUST-754 Accept references in insert and replace methods (breaking)
    • RUST-796 Provide easy way to reborrow session in between cursor iterations (breaking)
    • RUST-52 Drivers sessions API
    • RUST-735 Collection helpers return Collection<T> (breaking)
    • RUST-662 Expose the Reason an Operation Fails Document Validation
    • RUST-836 Support the 'let' option for aggregate (#391)
    • RUST-1002 Allow authentication to all server types except arbiters

    Improvements

    • RUST-633 Update dependency on tokio to v1.x (breaking)
    • RUST-870 Deserialize server response directly from raw BSON bytes (#389) (breaking)
    • RUST-871 Serialize directly to BSON bytes in insert operations (#406)
    • RUST-766 Gate MONGODB-AWS authentication behind the aws-auth feature flag (breaking)
    • RUST-725 Use "hello" for handshake and heartbeat when an API version is declared (#380)
    • RUST-768 Pass versioned API parameters to getMore and transaction-continuing commands. (#397)
    • RUST-887 Use HashMap::contains in Error::contains_label (#386)
    • RUST-615 Upgrade typed-builder to 0.9.0
    • RUST-739 Don't re-export types from unstable dependencies (breaking)
    • RUST-742 Reduce size of Error and ErrorKind (breaking)
    • RUST-760 Refactor StreamAddress to ServerAddress enum (breaking)
    • RUST-757 Remove wait_queue_timeout (breaking)
    • RUST-761 Rename CreateCollectionOptions::validation to CreateCollectionOptions::validator (breaking)
    • RUST-764 Use unsigned integers for values that should always be positive (breaking)
    • RUST-765 Ensure API follows Rust API Guidelines (breaking)
    • RUST-784 Mark WriteConcern::validate as pub(crate) (breaking)
    • RUST-786 Update collation options to use custom types rather than integers and strings (breaking)
    • RUST-788 Accept impl AsRef<str> instead of &str (breaking)
    • RUST-791 Accept PathBuf instead of String for paths in options (breaking)
    • RUST-811 Add feature flags for chrono and uuid interop in bson
    • RUST-823 Reduce the default max_pool_size to 10 (breaking)
    • RUST-830 Consolidate error labels to Error::labels (breaking)
    • minor: update semver to 1.0 (thanks @dtolnay!)
    • RUST-719 Correct casing in ServerType variants (breaking)
    • RUST-705 Switch from err-derive to thiserror
    • RUST-658 Change estimated_document_count() to use the $collStats aggregation stage
    • RUST-536 Eliminate redundant clones
    • RUST-852 Move trait bounds to implementation instead of Collection struct (thanks @univerz for suggesting!)
    • RUST-695 Add test that ensures the error returned from being evicted from the WaitQueue is retryable
    • RUST-777 Fix race condition in pool-clear-clears-waitqueue.yml test
    • RUST-835 Bump maxWireVersion for MongoDB 5.0
    • RUST-840 Buffer all reads and writes to sockets
    • RUST-847 Redact Debug for Credential
    • RUST-849 Remove extra fields from ConnectionPoolOptions included in events (breaking)
    • RUST-970 Upgrade to hmac 0.11 (thanks @seanpianka!)

    Bug fixes

    • RUST-591 ConnectionPoolOptions is used for event monitoring and pool internals (breaking)
    • RUST-759 DropCollectionOptions should skip serializing fields with a None value
    • RUST-714 Deadlock possible during retry
    • RUST-675 Server selection fails despite having a selectable server
    • RUST-717 Hint should be in deletes array for command, not in top-level document
    • RUST-718 Enforce update versus replace semantics
    • RUST-728 Inherit Collection options in find method
    • RUST-571 Fix race between SDAM and SRV Polling
    • RUST-853 Connection pools must be created and eventually marked ready for any server if a direct connection is used
    • RUST-570 Improve compile times of the test suite (#412)
    • RUST-793 Reduce size of returned futures (#417)
    • RUST-945 Check that explicit sessions were created on the correct client (#405)
    • RUST-926 Allow direct connections to hidden nodes

    Tasks

    • RUST-736 Update documentation for 2.0 release (#437)
    • RUST-730 Add MSRV policy to documentation (#444)
    • RUST-1001 Add warning about not polling futures to completion (#439)
    • RUST-162 Test driver on ARM Linux platforms
    • RUST-310 Rewrite URI options tests to use serde
    • RUST-814 Test on newer Ubuntu version(s)
    • RUST-820 Test against 5.0 servers
    • RUST-35 Add integration tests for writeConcern using command monitoring
    • RUST-652 Add script to run all linter tests
    • RUST-810 Add test for security-sensitive command monitoring event redaction
    • RUST-795 Update versioned api connection examples (#400)
    • RUST-670 Expect unified test format operations to succeed (#388)
    • RUST-665 Sync spec tests for field names with dots and dollars (#385)
    • RUST-734 Document support for sharded transactions
    • RUST-605 Update Versioned API Documentation
    • RUST-873 Test redaction of replies to security-sensitive commands
    • RUST-881 Run test suite with requireApiVersion 1
    • RUST-895 Update documentation for Time Series
    • RUST-944 Integration tests for observeSensitiveCommands
    • RUST-749 Convert CRUD tests to unified format (#410)
    • RUST-773 Update CMAP spec tests to prevent cross-test failpoint interference (#395)
    • RUST-774 Allow tests to specify backgroundThreadIntervalMS to fix a race condition. (#396)
    • RUST-775 CMAP integration test waits for wrong event
    • RUST-859 Improve bson_util function consistency (#411)
    • RUST-905 Try reading the default server URI from a local file if $MONGODB_URI is unset (#409)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.3(Aug 25, 2021)

    This release bumps a number of security related dependencies, one of which was causing compilation failures because it involved on a now-yanked transitive dependency. See #433 for more details.

    The changes have been cherry-picked from commits on master contributed by @bugadani and @seanpianka (RUST-682 and RUST-970 respectively), thanks again to you both!

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-beta.3(Aug 6, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update version of bson to v2.0.0-beta.3

    The 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 transactions on sharded topologies (#408)

    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+.

    Direct BSON serialization / deserialization (#389, #406)

    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.

    Versioned API support (#401)

    MongoDB 5.0 introduced the Versioned API, and this release includes support for specifying it via the ClientOptions.

    Full Release Notes

    New Features

    • RUST-97 Support sharded transactions recovery token (#398)
    • RUST-122 Support mongos pinning for sharded transactions (#383)
    • RUST-732 Mark the versioned API options public. (#401)
    • RUST-885 Support snapshot sessions (#390)
    • RUST-666 Add options for timeseries collection creation (#381)

    Improvements

    • RUST-901 Bump bson dependency to 2.0.0-beta.3
    • RUST-870 Deserialize server response directly from raw BSON bytes (#389) (breaking)
    • RUST-871 Serialize directly to BSON bytes in insert operations (#406)
    • RUST-725 Use "hello" for handshake and heartbeat when an API version is declared (#380)
    • RUST-768 Pass versioned API parameters to getMore and transaction-continuing commands. (#397)
    • RUST-836 Support the 'let' option for aggregate (#391)
    • RUST-887 Use HashMap::contains in Error::contains_label (#386)

    Bugfixes

    • RUST-570 Improve compile times of the test suite (#412)
    • RUST-793 Reduce size of returned futures (#417)
    • RUST-945 Check that explicit sessions were created on the correct client (#405)

    Tasks

    • RUST-795 Update versioned api connection examples (#400)
    • RUST-670 Expect unified test format operations to succeed (#388)
    • RUST-665 Sync spec tests for field names with dots and dollars (#385)
    • RUST-734 Document support for sharded transactions
    • RUST-605 Update Versioned API Documentation
    • RUST-873 Test redaction of replies to security-sensitive commands
    • RUST-881 Run test suite with requireApiVersion 1
    • RUST-895 Update documentation for Time Series
    • RUST-944 Integration tests for observeSensitiveCommands
    • RUST-749 Convert CRUD tests to unified format (#410)
    • RUST-773 Update CMAP spec tests to prevent cross-test failpoint interference (#395)
    • RUST-774 Allow tests to specify backgroundThreadIntervalMS to fix a race condition. (#396)
    • RUST-775 CMAP integration test waits for wrong event
    • RUST-859 Improve bson_util function consistency (#411)
    • RUST-905 Try reading the default server URI from a local file if $MONGODB_URI is unset (#409)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-beta.2(Jun 25, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update version of bson to v2.0.0-beta.2

    The 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.

    Enable passing 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.

    Remove default generic type of 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.

    Eliminate redundant clones (RUST-536)

    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.

    Move trait bounds from 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.

    Full Release Notes

    Bugfixes

    • RUST-851 Remove default generic type of Collection (breaking)
    • RUST-571 Fix race between SDAM and SRV Polling
    • RUST-853 Connection pools must be created and eventually marked ready for any server if a direct connection is used

    New Features

    • RUST-662 Expose the Reason an Operation Fails Document Validation

    Improvements

    • RUST-858 Enable passing options to builder methods (breaking)
    • RUST-536 Eliminate redundant clones
    • RUST-852 Move trait bounds to implementation instead of Collection struct (thanks @univerz for suggesting!)
    • RUST-695 Add test that ensures the error returned from being evicted from the WaitQueue is retryable
    • RUST-777 Fix race condition in pool-clear-clears-waitqueue.yml test
    • RUST-790 Rename ServerApiVersion variants to V1, V2, etc.
    • RUST-835 Bump maxWireVersion for MongoDB 5.0
    • RUST-840 Buffer all reads and writes to sockets
    • RUST-847 Redact Debug for Credential
    • RUST-849 Remove extra fields from ConnectionPoolOptions included in events (breaking)

    Tasks

    • RUST-162 Test driver on ARM Linux platforms
    • RUST-310 Rewrite URI options tests to use serde
    • RUST-814 Test on newer Ubuntu version(s)
    • RUST-820 Test against 5.0 servers
    • RUST-35 Add integration tests for writeConcern using command monitoring
    • RUST-652 Add script to run all linter tests
    • RUST-810 Add test for security-sensitive command monitoring event redaction
    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Aug 2, 2021)

    This release fixes the security issue identified in RUST-591 / RUST-847 (CVE-2021-20332). It is recommended that all users of the 1.x driver upgrade to this version to receive the fix. Note that this was also already fixed in v2.0.0-beta.

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-beta.1(Jun 1, 2021)

    Description

    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.

    Highlighted changes

    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.

    Update version of bson to v2.0.0-beta.1

    The 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.

    Replica Set Transactions (RUST-90)

    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.

    Reduce the default 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.

    Full Release Notes

    New features

    • RUST-90 Implement Replica Set transactions
    • RUST-824 Add Snapshot variant to ReadConcernLevel enum

    Improvements

    • RUST-811 Add feature flags for chrono and uuid interop in bson (breaking)
    • RUST-823 Reduce the default max_pool_size to 10 (breaking)
    • RUST-830 Consolidate error labels to Error::labels (breaking)
    • minor: update semver to 1.0 (thanks @dtolnay!)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-beta(May 14, 2021)

    Description

    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.

    Highlighted breaking changes

    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.

    Update version of bson to v2.0.0-beta

    The 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.

    Ensure API meets the Rust API Guidelines (RUST-765)

    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.

    Various error API improvements (RUST-739, RUST-765)

    Several improvements were made to the ErrorKind enum according to the guidelines to provide a more consistent and stable API:

    • The variants no longer wrap error types from unstable dependencies (C-STABLE)
    • The variant are named more consistently (C-WORD-ORDER)
      • Drop redundant Error suffix from each variant name
    • Redundant error variants were consolidated

    The total list of breaking changes is as follows:

    • All error variants dropped the "Error" suffix (e.g. ErrorKind::ServerSelectionError => ErrorKind::ServerSelection)
    • ErrorKind::ArgumentError => ErrorKind::InvalidArgument
      • ErrorKind::InvalidHostname => removed, consolidated into ErrorKind::InvalidArgument
    • ErrorKind::BsonDecode => ErrorKind::BsonDeserialization
    • ErrorKind::BsonEncode => ErrorKind::BsonSerialization
    • ErrorKind::ResponseError => ErrorKind::InvalidResponse
    • ErrorKind::DnsResolve(trust_dns_resolver::error::ResolveError) => ErrorKind::DnsResolve { message: String }
      • ErrorKind::InvalidDnsName => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::NoDnsResults => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::SrvLookupError => removed, consolidated into ErrorKind::DnsResolve
      • ErrorKind::TxtLookupError => removed, consolidated into ErrorKind::DnsResolve
    • ErrorKind::RustlsConfig(rustls::TLSerror) => ErrorKind::InvalidTlsConfig { message: String }
      • ErrorKind::ParseError => removed, consolidated into ErrorKind::InvalidTlsConfig
    • ErrorKind::WaitQueueTimeoutError => removed, the wait_queue_timeout option is no longer supported (RUST-757)
    • ErrorKind::OperationError => removed, consolidated into ErrorKind::InvalidResponse and ErrorKind::Internal as appropriate

    Stabilize or eliminate public dependencies on unstable types (C-STABLE, RUST-739)

    The 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:

    • Cursor types now implement the 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.
      • The 2.0 version of the driver will continue to depend on 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.
      • It's possible no changes will need to be made in the driver to transition to std::Stream. See (https://github.com/rust-lang/futures-rs/issues/2362)
    • ErrorKind variants that wrapped unstable errors were removed or refactored (see above)
    • Introduced a ResolverConfig type that opaquely wraps a trust_dns_resolver::ResolverConfig
    • TlsOptions::into_rustls_config was removed from the public API

    Wrap Error::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.

    Options builders Improvements (RUST-615)

    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:

    • the builder methods for Option<T> fields now accept T instead of impl Into<Option<T>>
      • previously, every method required impl Into<T>, so fields that were options required the explicit Some(...) to enable type inference on the interior type.
      • As part of this, the builder methods for T also just accept T, rather than Into<T>, allowing for type inference
    • incomplete .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();
    

    Accept 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.

    Return types that implement 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.

    Refactor 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.

    Full Release Notes

    New features

    • RUST-808 Upgrade bson to 2.0.0-beta (breaking)
    • RUST-615 Upgrade typed-builder to 0.9.0 (breaking)
    • RUST-738 Implement Clone on BSON error types (breaking)
    • RUST-740 Return Deserialize types from list_databases and list_collections (breaking)
    • RUST-754 Accept references in insert and replace methods (breaking)
    • RUST-796 Provide easy way to reborrow session in between cursor iterations (breaking)

    Improvements

    • RUST-739 Don't re-export types from unstable dependencies (breaking)
    • RUST-742 Reduce size of Error and ErrorKind (breaking)
    • RUST-760 Refactor StreamAddress to ServerAddress enum (breaking)
    • RUST-757 Remove wait_queue_timeout (breaking)
    • RUST-761 Rename CreateCollectionOptions::validation to CreateCollectionOptions::validator (breaking)
    • RUST-764 Use unsigned integers for values that should always be positive (breaking)
    • RUST-765 Ensure API follows Rust API Guidelines (breaking)
    • RUST-784 Mark WriteConcern::validate as pub(crate) (breaking)
    • RUST-786 Update collation options to use custom types rather than integers and strings (breaking)
    • RUST-788 Accept impl AsRef<str> instead of &str (breaking)
    • RUST-791 Accept PathBuf instead of String for paths in options (breaking)

    Bug fixes

    • RUST-591 ConnectionPoolOptions is used for event monitoring and pool internals (breaking)
    • RUST-759 DropCollectionOptions should skip serializing fields with a None value
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-alpha.1(Apr 9, 2021)

    Description

    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

    Release Notes

    Breaking Changes

    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> }
    

    Improved Error Matching (RUST-679)

    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!()
    }
    

    New Features

    • RUST-52 Drivers sessions API
    • RUST-735 Collection helpers return Collection<T> (breaking)

    Improvements

    • RUST-679 Simplify error API to ease pattern matching (breaking)
    • RUST-719 Correct casing in ServerType variants (breaking)
    • RUST-705 Switch from err-derive to thiserror
    • RUST-658 Change estimated_document_count() to use the $collStats aggregation stage

    Bug Fixes

    • RUST-714 Deadlock possible during retry
    • RUST-675 Server selection fails despite having a selectable server
    • RUST-717 Hint should be in deletes array for command, not in top-level document
    • RUST-718 Enforce update versus replace semantics
    • RUST-728 Inherit Collection options in find method
    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Apr 6, 2021)

    Description

    The MongoDB Rust driver team is pleased to announce the v1.2.1 release of the driver. This release fixes a few high priority issues, so it is highly recommended that all users of the 1.x driver upgrade to use this version.

    Bug Fixes

    • RUST-714 Fix a possible deadlock that could occur during retry
    • RUST-728 Inherit collection options in find helpers and count_documents
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Feb 16, 2021)

    Description

    The MongoDB Rust driver team is pleased to announce the v1.2.0 release of the driver.

    Release Notes

    Serde Integration Improvements

    This release contains several improvements to the driver's integration with Serde.

    • RUST-562 Return deserializable data types from find methods
    • RUST-561 Accept serializable data types as arguments to insert methods

    Connection Pooling Improvements

    This release contains several bug fixes and improvements to the connection pooling behavior in the driver. These improvements should both improve performance and also reduce the risk of “connection storms”.

    Some highlighted changes:

    • The driver was erroneously holding onto the mutex on the connection pool while establishing connections, greatly limiting throughput. This has been fixed, so now the pool may be used even when new connections are being established. (RUST-542)
    • Concurrent connection creation is now limited to 2 at a time, reducing the spike in connections that can happen after an increase in load, a primary election, or a reduction in throughput server-side. This limit also favors the reuse of existing connections over concurrently creating large amounts of connections, which in initial benchmarks is shown to have a positive impact on throughput. (RUST-556)
    • The server selection algorithm now considers the load of suitable servers when choosing among them, opting for nodes currently experiencing less load. This should more evenly distribute the workload across the deployment. (RUST-575)
    • Once the driver notices a server has gone down, it now “pauses” the associated connection pool, ensuring no new connection establishment attempts can be made against that server until it enters a known state again. Previously, there was a window in which these connection establishments could still be attempted even after the driver noticed that a server went down, and these establishment attempts could put unnecessary strain on such servers that were likely already struggling. (RUST-690)
    • The driver no longer incorrectly uses the “maxPoolSize” URI option to set “minPoolSize”. (RUST-566)

    Other New Features

    Improvements

    • RUST-623 Upgrade os_info to 3.0.1
    • RUST-690 Pause connection pool when server is marked Unknown
    • RUST-613 Upgrade typed-builder to 0.4.0
    • RUST-598 Perform handshake when establishing monitoring connections
    • RUST-562 Exclude unnecessary files

    Bug Fixes

    • RUST-592 Fix race condition in server monitoring
    • RUST-576 Fix count_document fails when writeConcern set on Collection
    • RUST-565 Properly report connection closures due to error
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-alpha(Jan 30, 2021)

    Description

    The MongoDB Rust driver team is pleased to announce the v2.0.0-alpha release of the driver, with support for tokio 1.x.

    Release Notes

    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.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Sep 1, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the v1.1.1 release of the driver.

    Release Notes

    Bug Fixes

    • RUST-544 Ensure correct termination of monitoring tasks
    • #241 remove accidental dependency on openssl
    • RUST-541 Include async runtime information in client metadata
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Aug 19, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the v1.1.0 release of the driver.

    Release Notes

    In addition to the changes for v1.1.0-beta, the following changes were made in v1.1.0:

    Bug Fixes

    • RUST-384 Close connection which was dropped during command execution (#214)
    • RUST-530 Decrement connection count when connection is dropped due to unfinished operation

    New Features

    • RUST-51 Implement retryable writes
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0-beta(Jul 31, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the v1.1.0-beta release of the driver.

    Release Notes

    Bug fixes

    • RUST-8 Create/modify collection helpers needs to support creating "validators"
    • RUST-524 Add non_exhaustive label to structs and enums missing it

    New Features

    • RUST-13 Add "indexOptionDefaults" to createCollection()
    • RUST-128 Implement retryable reads
    • RUST-359 Implement MONGODB-AWS authentication support
    • RUST-362 Allow passing hint to findAndModify operations
    • RUST-372 Allow passing hint to delete operations
    • RUST-376 Allow pasing hint to update operations
    • RUST-370 Add "errInfo" field to write concern errors
    • RUST-483 Allow alternate SRV resolver configs

    Improvements

    • RUST-170 Enable and configure TCP Keepalive by default
    • RUST-479 Lift restriction on authSource without credentials
    • RUST-502 Standardize behavior of empty authSource URI option
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jun 8, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the first stable release of the driver, v1.0.0. This release marks the general availability of the driver. Additionally, per semver requirements, no breaking API changes will be made to the 1.x branch of the driver.

    Major Features

    See the releases notes for v0.11.0 for recent changes made to the driver before this release.

    Special thanks

    Thanks to everyone who contributed code and/or advice along our path to 1.0, including @nevi-me, @ttdonovan, @petoknm, @judy2k, @freakmaxi, @brunobell, @andywswan, @UmerMIB, @DarkEld3r, @yoshuawuyts, and @LucioFranco!

    Source code(tar.gz)
    Source code(zip)
  • v0.11.0(Jun 3, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the first release candidate of the driver, v0.11.0.

    Major Features

    In preparation of stabilizing the API of the driver, we made a number of breaking changes. The individual changes are listed below in the release notes, each with a short description of why we made the change.

    Release Notes

    Breaking Changes

    • RUST-261 Mark enums and options struct as non-exhaustible
      • In order to ensure that adding new variants to our enums (e.g. mongodb::error::ErrorKind) in the future will not cause breaking changes for users who are pattern matching them, we've marked some of them as non-exhaustive. Additionally, in order to be able to add new options to our options structs in the future, we've also marked them as non-exhaustive. This has the side-effect of making them impossible to instantiate with struct literals. The workaround is to use the auto-generated builder pattern API for them, which continues to be available as before.
    • RUST-434 Rewrite ReadConcern as a struct
      • In order to allow us to add any potential new read concern options that might be added in the future, we've changed mongodb::options::ReadConcern to be a (non-exhaustive) struct rather than an enum. To ensure that it's easy to use, we've added a helper method for each ReadConcern level to faciliatate construction.
    • RUST-433 Rename "Tag" Acknowledgement case to "Custom"
      • The original name for this enum variant was a bit misleading. The official documentation for write concerns has since been updated to describe this type of write concern as "custom" rather than "tag", so we changed the API of the driver accordingly.
    • RUST-435 Standardize on options exporting strategy
      • We previously exported the authentication options exposed by the driver under the namespace mongodb::options::auth, whereas the rest of the driver's options were exported directly from mongodb::options. We now export the auth options directly from mongodb::options for consistency.

    Bug fixes

    • RUST-408 Sync API not included in the generated documentation

    New Features

    • RUST-289 Implicit Sessions
    • RUST-392 Suppress "ns not found" errors
    • RUST-396 run_command should parse server errors
    • RUST-409 Add DriverInfoOptions to client metadata

    Improvements

    • RUST-439 Return errors when unacknowledged write concerns are passed in
    Source code(tar.gz)
    Source code(zip)
  • v0.10.0(May 5, 2020)

    Description

    The MongoDB Rust driver team is pleased to announce the first beta of the driver, v0.10.0.

    Major Features

    Async API

    The Rust driver now provides an async API which can be used with either tokio or async-std. By default, the driver uses tokio primitives for things like TcpStreams, although the runtime still must be started before calling into the driver API. To use async-std instead of tokio, specify the following in your Cargo.toml:

    [dependencies.mongodb]
    version = "0.10.0"
    default-features = false
    features = ["async-std-runtime"]
    

    Sync API

    The sync API from previous versions of the driver has been moved to the sync module and gated under the sync feature. To enable it, specify the following in your Cargo.toml:

    [dependencies.mongodb]
    version = "0.10.0"
    default-features = false
    features = ["sync"]
    

    The sync API wraps the async API and blocks on the results of the async API method calls. It uses async-std under the hood.

    Release Notes

    Bug fixes

    • RUST-397 $readPreference not being set against some topology types

    New Feature

    • RUST-104 Support polling SRV records for mongos discovery
    • RUST-214 Implement non-blocking connection pooling
    • RUST-303 Implement async wire protocol
    • RUST-298 Implement non-blocking server discovery and monitoring
    • RUST-300 Implement async DNS
    • RUST-322 Add async client/database API
    • RUST-323 Add async collection API
    • RUST-324 Add async cursor API
    • RUST-215 Implement sync operations wrapping async API

    Improvement

    • RUST-286 Use system DNS resolver instead of Google
    • RUST-306 Disable default features on pbkdf2 crate
    • RUST-333 Improve invalid URI option error message
    • RUST-351 Add 'allowDiskUse' option to find command
    • RUST-352 Support for 'authorizedDatabases' option

    Contributors

    Thanks to @judy2k, @nevi-me, and @UmerMIB for the pull requests!

    Source code(tar.gz)
    Source code(zip)
Owner
mongodb
mongodb
Cassandra (CQL) driver for Rust, using the DataStax C/C++ driver under the covers.

cassandra-cpp This is a maintained Rust project that exposes the DataStax cpp driver at https://github.com/datastax/cpp-driver/ in a somewhat-sane cra

null 93 Jan 7, 2023
This is a maintained rust project that exposes the cpp driver at cpp-driver in a somewhat-sane crate.

cassandra-rs This is a maintained rust project that exposes the cpp driver at https://github.com/datastax/cpp-driver/ in a somewhat-sane crate. For th

Tupshin Harper 51 Aug 20, 2020
Official Skytable client driver for Rust

Skytable client Introduction This library is the official client for the free and open-source NoSQL database Skytable. First, go ahead and install Sky

Skytable 29 Nov 24, 2022
Blazingly fast data generation & seeding for MongoDB

Planter Blazingly fast and simple data generation & seeding for MongoDB Installation Use the package manager cargo to install planter. Add the followi

Valencian Digital 4 Jan 12, 2022
The most efficient, scalable, and fast production-ready serverless REST API backend which provides CRUD operations for a MongoDB collection

Optimal CRUD Mongo Goals of This Project This is meant to be the most efficient, scalable, and fast production-ready serverless REST API backend which

Evaluates2 1 Feb 22, 2022
Teach your PostgreSQL database how to speak MongoDB Wire Protocol

“If it looks like MongoDB, swims like MongoDB, and quacks like MongoDB, then it probably is PostgreSQL.” ?? Discord | Online Demo | Intro Video | Quic

Felipe Coury 261 Jun 18, 2023
Automatically publish MongoDB changes to Redis for Meteor.

changestream-to-redis Warning The project is currently in its alpha phase. There are no production loads using it yet nor any large-scale tests were c

Radosław Miernik 8 Jul 29, 2023
An ArangoDB driver for Rust

Rincon Rincon is an ArangoDB driver for Rust. It enables low level access to ArangoDB in a typesafe and Rust idiomatic manner. The name Rincon is deri

Innoave 35 Mar 21, 2021
TDS 7.2+ (mssql / Microsoft SQL Server) async driver for rust

Tiberius A native Microsoft SQL Server (TDS) client for Rust. Supported SQL Server versions Version Support level Notes 2019 Tested on CI 2017 Tested

Prisma 189 Dec 25, 2022
Asyncronous Rust Mysql driver based on Tokio.

mysql-async Tokio based asynchronous MySql client library for rust programming language. Installation Library hosted on crates.io. [dependencies] mysq

Anatoly I 292 Dec 30, 2022
Native PostgreSQL driver for the Rust programming language

Rust-Postgres PostgreSQL support for Rust. postgres Documentation A native, synchronous PostgreSQL client. tokio-postgres Documentation A native, asyn

Steven Fackler 2.8k Jan 8, 2023
cogo rust coroutine database driver (Mysql,Postgres,Sqlite)

cdbc Coroutine Database driver Connectivity.based on cogo High concurrency,based on coroutine No Future<'q,Output=*>,No async fn, No .await , no Poll*

co-rs 10 Nov 13, 2022
This is an Oracle database driver for Rust based on ODPI-C

Rust-oracle This is an Oracle database driver for Rust based on ODPI-C. Change Log See ChangeLog.md. Build-time Requirements C compiler. See Compile-t

Kubo Takehiro 138 Dec 23, 2022
Easy to use rust driver for arangoDB

arangors arangors is an intuitive rust client for ArangoDB, inspired by pyArango. arangors enables you to connect with ArangoDB server, access to data

fMeow 116 Jan 1, 2023
A Rust port of Pimoroni's uc8151 driver

uc8151-rs - a no-std Rust library for the UC8151(IL0373) e-ink display This is a Rust port of the Pimoroni UC8151 library. UC8151 is also sometimes re

null 6 Dec 15, 2022
ENC28J60 Linux network driver written in Rust.

enc28j60rs ENC28J60 Linux ethernet driver written in Rust. Tested with Raspberry Pi 4 Model B + Linux kernel 6.2.8 + Raspberry Pi OS AArch64. Kernel T

Ryo Munakata 11 May 1, 2023
MIPI Display Serial Interface unified driver

mipidsi This crate provides a generic display driver to connect to TFT displays that implement the MIPI DSI. Uses display_interface to talk to the har

Aleš Katona 31 Dec 20, 2022
TTVM Intermediate Representation driver

ttir - TTVM IR Driver ttir is driver for the TTVM IR located in ttvm. Usage Run the following command in your shell: cargo install ttir Features Easy

maDeveloper 1 Nov 2, 2021
e-paper/e-ink monitor linux driver

Ardoise: e-paper/e-ink monitor Goal: Create a e-paper/e-ink monitorfor linux. My personal use is a typewriter. Written in Rust Latency is 0,2s when th

Cyril Jacquet 1 Dec 8, 2022