MongoDB: Part II

Learn how to take advantage of Mongodb and pass structs between Rust and Mongodb.

Other useful MongoDB commands

Besides inserting and finding documents, we can also update and delete them:

Press + to interact
use mongodb::{options::ClientOptions, Client};
use mongodb::bson::{self, doc, Bson};
use std::error::Error;
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
mongodb_init(3)?; // Needed for this playground to work
let client_uri = "mongodb://127.0.0.1:27017/?directConnection=true";
let mut client_options = ClientOptions::parse(&client_uri).await?;
client_options.app_name = Some("Rust Demo".to_string());
let client = mongodb::Client::with_options(client_options)?;
let new_doc = doc! {
"name": "John Doe",
"birth": 1985,
"salary": 36000.0,
};
let employees = client.database("company_database").collection("employees");
let insert_result = employees.insert_one(new_doc.clone(), None).await?;
let new_doc_id = insert_result.inserted_id;
// Update the document:
let update_result = employees.update_one(
doc! {
"_id": &new_doc_id
},
doc! {
"$set": { "salary": 38000.0 }
},
None,
).await?;
println!("Updated {} document", update_result.modified_count);
let employee = employees.find_one(
doc! {
"name": "John Doe"
},
None,
)
.await?
.expect("Missing document.");
println!("Employee's salary: {}", employee.get_f64("salary")?);
Ok(())
}

Here, we updated a record with update_one(). This method takes two BSON documents. The first finds the record to update, and the second has instructions for what to update. In this case, we only update the: salary ...