BsonUser Guide

Overview

Bson is an implementation of the BSON specification complete with BSON serialisation and deserialisation.

Note that BSON is an extention of JSON, and JSON can only represent a subset of the types supported by BSON.

Bson was created to support the development of the Fantom Factory MongoDB driver.

Quick Start

1). Create a text file called Example.fan:

using afBson

class Example {

  Void main() {
    docIn := [
      "_id"  : ObjectId(),
      "name" : "Dave",
      "age"  : 42
    ]

    // serialise BSON to a Buf
    buf := BsonIO().writeDoc(documentIn)

    // deserialise BSON from a stream
    docOut := BsonIO().readDoc(buf.flip.in)

    echo(docOut)
  }
}

2). Run Example.fan as a Fantom script from the command line:

C:\> fan Example.fan

[_id:53503531a8000b8b44000001, name:Dave, age:42]

Usage

The BsonIO class (de)serialises BSON documents to and from Fantom using the following mapping:

BSON       <->    Fantom
-------------------------------
ARRAY      <->    sys::List      
BINARY     <-> afBson::Binary    
BOOLEAN    <->    sys::Bool      
CODE       -->    sys::Str      (read only)  
DATE       <->    sys::DateTime  
DOCUMENT   <->    sys::Map       
DOUBLE     <->    sys::Float     
INTEGER_32 -->    sys::Int      (read only)
INTEGER_64 <->    sys::Int
MAX_KEY    <-> afBson::MaxKey    
MIN_KEY    <-> afBson::MinKey    
NULL       <->         null      
OBJECT_ID  <-> afBson::ObjectId  
REGEX      <->    sys::Regex     
STRING     <->    sys::Str       
TIMESTAMP  <-> afBson::Timestamp 

Bson takes care of all the tricky Endianness. All BSON objects may be serialised to and from strings using Fantom's standard serialisation techniques.

Implementation Notes

Deprecated BSON constructs (CODE_W_SCOPE, DB_POINTER, SYMBOL, and UNDEFINED) are ignored and have no Fantom representation.

  • INTEGER_32 values are read as Fantom (64-bit) Ints
  • CODE objects are read as Fantom Strs
  • REGEX flags are read and converted into embedded character flags (e.g., /myregex/im is converted to /(?im)myregex/)

If these objects are subsequently written back (to MongoDB), be aware that their backing storage type will change to represent their new Fantom type. This is only noteworthy if other, non Fantom, drivers are reading / writing values to / from the database.

See Java's Pattern Class for a list of supported regex flags (dimsuxU).

Special Mentions

The Fantom Factoy BSON library was inspired by fantomongo by Liam Staskawicz.