[Rust 알아가기] 몽고디비 접속 예제
Cargo.toml
------------------------------------------
[dependencies.mongodb]
version = "1.1.1"
default-features = false
features = ["sync"]
main.rs
--------------------------------------------
use mongodb::{
bson::{doc, Bson},
sync::Client,
};
fn main() -> mongodb::error::Result<()> {
let client = Client::with_uri_str("mongodb://localhost:27017")?;
let database = client.database("mobdw");
let collection = database.collection("books");
let docs = vec![
doc! { "title": "반도", "author": "George Orwell" },
doc! { "title": "Animal Farm", "author": "George Orwell" },
doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
];
collection.insert_many(docs, None)?;
let cursor = collection.find(doc! { "author": "George Orwell" }, None)?;
for result in cursor {
match result {
Ok(document) => {
if let Some(title) = document.get("title").and_then(Bson::as_str) {
println!("title: {}", title);
} else {
println!("no title found");
}
}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
-------------------------------------------------------------------