Rust: mongodb ドライバーの使い方


こちらのサンプルを改造してみました。
Announcing our Rust Driver: Version 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
Cargo.toml
[package]
name = "mongodb_sample"
version = "0.1.0"
edition = "2018"


[dependencies]
mongodb = "1.0.0"
tokio = "*"
src/main.rs
// --------------------------------------------------------------------
/*
    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`
*** 開始 ***
*** 終了 ***

mongo cli でデータが作成されたことを確認

$ 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" : "みけ" }
>