struct

BSON

Inherits Comparable / Iterable / Enumerable / Struct / Value / Object

BSON is a binary format in which zero or more ordered key/value pairs are stored as a single entity.

BSON [bee · sahn], short for Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays. BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON spec. For ex­ample, BSON has a Date type and a BinData type.

See: http://bsonspec.org/

require "bson"

data = BSON.new({
  hello: "world",
  time:  Time.utc,
  name:  BSON.new({
    first_name: "John",
    last_name:  "Doe",
  }),
  fruits: ["Orange", "Banana"],
})

puts data.to_json
# => {"hello":"world","time":{"$date":"2020-05-18T07:32:13.621000000Z"},"name":{"first_name":"John","last_name":"Doe"},"fruits":["Orange","Banana"]}

Constructors

new(data : Bytes | Nil = nil, validate? = false)

Allocate a BSON instance from a byte array.

NOTE: The byte array is cloned.

data = "160000000378000E0000000261000200000062000000".hexbytes
io = IO::Memory.new(data)
bson = BSON.new(io)
puts bson.to_json # => {"x":{"a":"b"}}
Source
new(io : IO)

Allocate a BSON instance from an IO

data = "160000000378000E0000000261000200000062000000".hexbytes
bson = BSON.new(data)
puts bson.to_json # => {"x":{"a":"b"}}
Source
new(tuple : NamedTuple)

Allocate a BSON instance from a NamedTuple.

puts BSON.new({
  hello: "world",
}).to_json # => {"hello":"world"}
Source
new(h : Hash)

Allocate a BSON instance from a Hash.

puts BSON.new({
  "hello" => "world",
}).to_json # => {"hello":"world"}
Source
new(bson : BSON)

No-op

Source
new(ary : Array)

Allocate a BSON instance from an Array.

puts BSON.new([1, 2, 3]).to_json # => [1,2,3]
Source
new(serializable : BSON::Serializable)

Allocate a BSON instance from an instance of BSON::Serializable.

Source

Class methods

from_json(json : String)

Allocate a BSON instance from a relaxed extended json representation.

NOTE: see https://github.com/mongodb/specifications/blob/master/source/extended-json.rst

bson = BSON.from_json(%({
  "_id": {
    "$oid": "57e193d7a9cc81b4027498b5"
  },
  "String": "string",
  "Int": 42,
  "Double": -1.0
}))
puts bson.to_json # => {"_id":{"$oid":"57e193d7a9cc81b4027498b5"},"String":"string","Int":42,"Double":-1.0}
Source

Instance methods

<=>(other : BSON)

Compare with another BSON value.

puts BSON.new({a: 1}) &lt;=&gt; BSON.new({a: 1}) # =&gt; 0
puts BSON.new({a: 1}) &lt;=&gt; BSON.new({b: 2}) # =&gt; -1
Source
[](key : String | ::Symbol) : Value

Return the element with the given key.

NOTE: Will raise if the key is not found.

bson = BSON.new({ key: &quot;value&quot; })
puts bson[&quot;key&quot;] # =&gt;&quot;value&quot;
puts bson[&quot;nope&quot;] # =&gt; Unhandled exception: Missing bson key: nope (Exception)
Source
[]=(key : String | ::Symbol, value)

Append a key/value pair.

bson = BSON.new
bson[&quot;key&quot;] = &quot;value&quot;
puts bson.to_json # =&gt; {&quot;key&quot;:&quot;value&quot;}
Source
[]?(key : String | ::Symbol) : Value | Nil

Return the element with the given key, or nil if the key is not present.

bson = BSON.new({key: &quot;value&quot;})
puts bson[&quot;key&quot;]?  # =&gt; &quot;value&quot;
puts bson[&quot;nope&quot;]? # =&gt; nil
Source
append(other : BSON)

Append the contents of another BSON instance.

bson = BSON.new
other_bson = BSON.new({key: &quot;value&quot;, key2: &quot;value2&quot;})
bson.append(other_bson)
puts bson.to_json # =&gt; {&quot;key&quot;:&quot;value&quot;,&quot;key2&quot;:&quot;value2&quot;}
Source
append

Append one or more key/value pairs.

NOTE: more efficient for appending multiple values than calling []= individually.

bson = BSON.new
bson.append(key: &quot;value&quot;, key2: &quot;value2&quot;)
puts bson.to_json # =&gt; {&quot;key&quot;:&quot;value&quot;,&quot;key2&quot;:&quot;value2&quot;}
Source
append_array(key : String | ::Symbol, value : BSON)

Append a key/value pair and declare it as a BSON array.

Source
clear

Clears the BSON instance.

Source
data

Underlying bytes

Source
dig(key : String | ::Symbol, *subkeys)

Traverses the depth of a structure and returns the value, otherwise raises.

Source
dig?(key : String | ::Symbol, *subkeys)

Traverses the depth of a structure and returns the value. Returns nil if not found.

Source
each

Yield each key/value pair to the block.

NOTE: Underlying BSON code as well as the binary subtype are also yielded to the block as additional arguments.

BSON.new({
  a: 1,
  b: &quot;2&quot;,
  c: Slice[0_u8, 1_u8, 2_u8],
}).each { |(key, value, code, binary_subtype)|
  puts &quot;#{key} =&gt; #{value}, code: #{code}, subtype: #{binary_subtype}&quot;
# a =&gt; 1, code: Int32, subtype:
# b =&gt; 2, code: String, subtype:
# c =&gt; Bytes[0, 1, 2], code: Binary, subtype: Generic
}
Source
each

Returns an Iterator over each key/value pair.

Source
empty?

Returns true if the BSON is empty.

Source
has_key?(key : String | ::Symbol) : Bool

Returns true when key given by key exists, otherwise false.

Source
size

Return the size of the BSON instance in bytes.

Source
to_canonical_extjson

Serialize this BSON instance into a canonical extended json representation.

NOTE: see https://github.com/mongodb/specifications/blob/master/source/extended-json.rst

bson = BSON.from_json(%({
  &quot;Int&quot;: 42,
  &quot;Double&quot;: -1.0
}))
puts bson.to_canonical_extjson # =&gt; {&quot;Int&quot;:{&quot;$numberLong&quot;:&quot;42&quot;},&quot;Double&quot;:{&quot;$numberDouble&quot;:&quot;-1.0&quot;}}
Source
to_h

Returns a Hash representation.

NOTE: This function is recursive and will convert nested BSON to hash objects.

bson = BSON.new({
  a: 1,
  b: &quot;2&quot;,
  c: {
    d: 1,
  },
})
pp bson.to_h # =&gt; {&quot;a&quot; =&gt; 1, &quot;b&quot; =&gt; &quot;2&quot;, &quot;c&quot; =&gt; { &quot;d&quot; =&gt; 1}}
Source
to_json(builder : JSON::Builder, *, array = false)

ameba:disable Metrics/CyclomaticComplexity

Source
validate!

Validate that the BSON is well-formed.

bson = BSON.new(&quot;140000000461000D0000001030000A0000000000&quot;.hexbytes)
bson.validate!
# =&gt; Unhandled exception: Invalid BSON (overflow) (Exception)
Source

Nested types