MongoDB with the Rust driver
Uses the mongodb crate 3.9. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”mongodb://app:secret@mongo.example.com:27017/shop?authSource=adminmongodb://app:secret@machnosql.example.com:27017/shop?authSource=adminThe address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'cargo runSource
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
//! Orders example for MongoDB, unchanged on MachNoSQL.
use futures::TryStreamExt;use mongodb::bson::{Document, doc};use mongodb::Client;
#[tokio::main]async fn main() -> mongodb::error::Result<()> { let uri = std::env::var("MONGODB_URI").expect("set MONGODB_URI"); let client = Client::with_uri_str(uri).await?; let orders = client.database("shop").collection::<Document>("orders");
orders.delete_many(doc! {}).await?; orders .insert_many([ doc! { "customer": "ada", "item": "keyboard", "qty": 1, "price": 49.0 }, doc! { "customer": "ada", "item": "mouse", "qty": 2, "price": 19.5 }, doc! { "customer": "linus", "item": "monitor", "qty": 1, "price": 199.0 }, ]) .await?;
println!("{:?}", orders.find_one(doc! { "item": "mouse" }).await?); orders .update_one(doc! { "item": "mouse" }, doc! { "$inc": { "qty": 1 } }) .await?;
let pipeline = [ doc! { "$group": { "_id": "$customer", "revenue": { "$sum": { "$multiply": ["$qty", "$price"] } } } }, doc! { "$sort": { "revenue": -1 } }, ]; let mut rows = orders.aggregate(pipeline).await?; while let Some(row) = rows.try_next().await? { println!("{row}"); } Ok(())}[package]name = "machnosql-example-mongodb"version = "0.1.0"edition = "2024"publish = false
[dependencies]futures = "0.3.34"mongodb = "3.9.1"tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] }