bson 0.6.1

Encoding and decoding support for BSON in Rust


Build Status

Encoding and decoding support for BSON in Rust

Useful links


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

bson = "0.6.1"


Link the library in

#[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))?