Rust: 使用MongoDB驱动程序的方法.
在此我们宣布更新了我们的 Rust 驱动程序:版本 1.0。
我在下一个环境中进行了确认。
在旧版本中,无法通过编译。
$ uname -a
Linux *** 5.7.10-arch1-1 #1 SMP PREEMPT Wed, 22 Jul 2020 19:57:42 +0000 x86_64 GNU/Linux
$ rustc --version
rustc 1.45.0
$ cargo --version
cargo 1.45.0
[package]
name = "mongodb_sample"
version = "0.1.0"
edition = "2018"
[dependencies]
mongodb = "1.0.0"
tokio = "*"
// --------------------------------------------------------------------
/*
mongodb_sample/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("animals")
.collection("pets");
let new_pets = vec![
doc! { "type": "犬", "name": "しろ" },
doc! { "type": "猫", "name": "たま" },
doc! { "type": "猫", "name": "みけ" },
];
coll.insert_many(new_pets, None).await?;
eprintln! ("*** 終了 ***");
Ok(())
}
// --------------------------------------------------------------------
执行
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.14s
Running `target/debug/mongodb_sample`
*** 開始 ***
*** 終了 ***
确认在 MongoDB 命令行界面上已成功创建了数据。
$ mongo
> use animals
switched to db animals
> db.pets.find()
{ "_id" : ObjectId("5f1b7edd00fec86e00bb2de8"), "type" : "犬", "name" : "しろ" }
{ "_id" : ObjectId("5f1b7edd002ae22200bb2de9"), "type" : "猫", "name" : "たま" }
{ "_id" : ObjectId("5f1b7edd00ae494700bb2dea"), "type" : "猫", "name" : "みけ" }
>