Encoding and decoding support for BSON in Rust
Rust
Latest commit 65071b8 Dec 13, 2016 @zonyitoo committed on GitHub Merge pull request #48 from fengcen/master
fix gethostname in windows.

README.md

bson-rs

Build Status crates.io crates.io

Encoding and decoding support for BSON in Rust

Useful links

Installation

This crate works with Cargo and can be found on crates.io with a Cargo.toml like:

[dependencies]
bson = "0.3.2"

Usage

Link the library in main.rs:

#[macro_use(bson, doc)]
extern crate bson;

Prepare your struct for Serde serialization:

#[derive(Serialize, Deserialize, Debug)]
pub struct Person {
    #[serde(rename = "_id")]  // Use MongoDB's special primary key field name when serializing 
    pub id: String,
    pub name: String,
    pub age: u32
}

Serialize the struct:

use bson;

let person = Person {
    id: "12345",
    name: "Emma",
    age: 3
};

let serialized_person = bson::to_bson(&person)?;  // Serialize

if let bson::Bson::Document(document) = serialized_person {
    mongoCollection.insert_one(document, None)?;  // Insert into a MongoDB collection
} else {
    println!("Error converting the BSON object into a MongoDB document");
}

Deserialize the struct:

// Read the document from a MongoDB collection
let person_document = mongoCollection.find_one(Some(doc! { "_id" => "12345" }), None)?
    .expect("Document not found");

// Deserialize the document into a Person instance
let person = bson::from_bson(bson::Bson::Document(person_document))?