Skip to content

Instantly share code, notes, and snippets.

@durka
Last active August 28, 2017 05:26
Show Gist options
  • Save durka/16ae71a07ec77878642343b5338e6144 to your computer and use it in GitHub Desktop.
Save durka/16ae71a07ec77878642343b5338e6144 to your computer and use it in GitHub Desktop.
[package]
name = "xxx"
version = "0.1.0"
authors = ["..."]
[dependencies]
bson = "0.9.0"
mongodb = "0.3.3"
#[macro_use(bson, doc)]
extern crate bson;
extern crate mongodb;
use bson::Bson;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
fn main() {
let client = Client::connect("localhost", 27017)
.expect("Failed to initialize standalone client.");
let coll = client.db("test").collection("movies");
let doc = doc! { "title" => "Jaws",
"array" => [ 1, 2, 3 ] };
// Insert document into 'test.movies' collection
coll.insert_one(doc.clone(), None)
.ok().expect("Failed to insert document.");
// Find the document and receive a cursor
let mut cursor = coll.find(Some(doc.clone()), None)
.ok().expect("Failed to execute find.");
let item = cursor.next();
// cursor.next() returns an Option<Result<Document>>
match item {
Some(Ok(doc)) => match doc.get("title") {
Some(&Bson::String(ref title)) => println!("{}", title),
_ => panic!("Expected title to be a string!"),
},
Some(Err(_)) => panic!("Failed to get next from server!"),
None => panic!("Server returned no results!"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment