使用 Rust 编写代码来创建 MongoDB 数据
[package]
name = "mongodb_create"
version = "0.1.0"
edition = "2018"
[dependencies]
mongodb = "1.0.0"
tokio = "*"
// --------------------------------------------------------------------
/*
mongodb_create/src/main.rs
Jul/25/2020
*/
// --------------------------------------------------------------------
use mongodb::{
bson::doc,
error::Result,
Client
};
#[tokio::main]
async fn main() -> Result<()> {
eprintln! ("*** 開始 ***");
let client =
Client::with_uri_str("mongodb://localhost:27017").await?;
let coll = client
.database("city")
.collection("saitama");
let new_cities = vec![
doc! {"key": "t1161", "name": "さいたま","population": 45298,"date_mod": "1956-6-12"},
doc! {"key": "t1162", "name": "所沢" ,"population": 21983,"date_mod": "1956-8-24"},
doc! {"key": "t1163", "name": "越谷" ,"population": 51287,"date_mod": "1956-3-9"},
];
coll.insert_many(new_cities, None).await?;
eprintln! ("*** 終了 ***");
Ok(())
}
// --------------------------------------------------------------------
执行
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.34s
Running `target/debug/mongodb_create`
*** 開始 ***
*** 終了 ***
在 mongo 的命令行界面中进行确认。
$ mongo
> use city
switched to db city
> db.saitama.find()
{ "_id" : ObjectId("5f1bf38b00c8509a003a3a47"), "key" : "t1161", "name" : "さいたま", "population" : 45298, "date_mod" : "1956-6-12" }
{ "_id" : ObjectId("5f1bf38b0077dbf3003a3a48"), "key" : "t1162", "name" : "所沢", "population" : 21983, "date_mod" : "1956-8-24" }
{ "_id" : ObjectId("5f1bf38b0054d9c9003a3a49"), "key" : "t1163", "name" : "越谷", "population" : 51287, "date_mod" : "1956-3-9" }