NoSQL and friends

RecipeCratesCategories
Connect to MongoDBmongodbcat-asynchronous cat-database cat-web-programming
Connect to Redisrediscat-database

Connect to MongoDB

mongodb mongodb-crates.io mongodb-github mongodb-lib.rs cat-asynchronous cat-database cat-web-programming

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

Connect to Redis

redis redis-crates.io redis-github redis-lib.rs

Redis-rs is a high level redis library for Rust. It provides convenient access to all Redis functionality through a very flexible but low-level API. It uses a customizable type conversion trait so that any operation can return results in just the type you are expecting. This makes for a very pleasant development experience.

use anyhow::Result;
use redis::Commands;

fn fetch_an_integer() -> redis::RedisResult<isize> {
    // `open` does not actually open a connection yet but it does perform some
    // basic checks on the URL that might make the operation fail.
    let client = redis::Client::open("redis://127.0.0.1/")?;
    // actually connect to redis
    let mut con = client.get_connection()?;
    // throw away the result, just make sure it does not fail
    let _: () = con.set("my_key", 42)?;
    // read back the key and return it.  Because the return value
    // from the function is a result for integer this will automatically
    // convert into one.
    con.get("my_key")
}

fn main() -> Result<()> {
    let my_int = fetch_an_integer()?;
    println!("{}", my_int);
    Ok(())
}