Rust: 更新 MongoDB 数据
[package]
name = "mongodb_update"
version = "0.1.0"
edition = "2018"
[dependencies]
mongodb = "1.0.0"
tokio = "*"
chrono = "0.4"
// --------------------------------------------------------------------
/*
mongodb_update/src/main.rs
Jul/26/2020
*/
// --------------------------------------------------------------------
use std::env;
use mongodb::{
bson::doc,
error::Result,
Client
};
use chrono::{Local, Date};
#[tokio::main]
async fn main() -> Result<()> {
eprintln! ("*** 開始 ***");
let args: Vec<_> = env::args().collect();
let key_in = &args[1];
let population_in = &args[2];
eprintln!("{}",key_in);
eprintln!("{}",population_in);
let client =
Client::with_uri_str("mongodb://localhost:27017").await?;
let coll = client
.database("city")
.collection("saitama");
let pp_in : i32 = population_in.parse().unwrap();
let date_mod: Date<Local> = Local::today();
println!("{}", date_mod);
let update_result = coll.update_one(
doc! { "key": key_in },
doc! {
"$set": {"population": pp_in, "date_mod": date_mod.to_string()}
},
None,
).await?;
println!("Updated {} document", update_result.modified_count);
eprintln! ("*** 終了 ***");
Ok(())
}
// --------------------------------------------------------------------
执行
$ cargo run t1163 8235100
Finished dev [unoptimized + debuginfo] target(s) in 0.14s
Running `target/debug/mongodb_update t1163 8235100`
*** 開始 ***
t1163
8235100
2020-07-26+09:00
Updated 1 document
*** 終了 ***
快速指南:使用Rust和MongoDB进行启动并运行