DEV Community

loading...

Connect to a single MongoDB instance from rust

kushalj profile image Kushal Joshi ・1 min read

The rust driver for Mongo is still in its infancy. It is well documented in terms of the signatures of each function and feature but very limited when it comes to examples. I spent way to long trying to make a simple connection to local and staging Mongo instances and the examples just don't work.

Solution:
They are missing the direct_connection option flag.

fn main() {
    // Set URI
    let uri = "mongodb://localhost:27017/";

    // Setup options
    let mut options = ClientOptions::parse(uri).unwrap();
    options.direct_connection = Some(true);

    // Create the Client
    let client = Client::with_options(options).unwrap();

    // Use the Client
    let _dbs = dbg!(client.list_database_names(None));
}

Note for noobs, you don't need the dbg!() wrapper - that is just to log the output easily. You can just:

let _dbs = client.list_database_names(None);

Discussion (1)

pic
Editor guide
Collapse
kydlaw profile image
Kydlaw

Thanks for the hint!