Class: BSON::Document

Inherits:
Hash
  • Object
show all
Defined in:
lib/bson/document.rb

Overview

Note:

The specification is: document ::= int32 e_list “x00”

This module provides behaviour for serializing and deserializing entire BSON documents, according to the BSON specification.

See Also:

Since:

  • 2.0.0

Instance Method Summary collapse

Constructor Details

#initialize(elements = nil) ⇒ Document

Instantiate a new Document. Valid parameters for instantiation is a hash only or nothing.

Examples:

Create the new Document.

BSON::Document.new(name: "Joe", age: 33)

Parameters:

  • elements (Hash) (defaults to: nil)

    The elements of the document.

Since:

  • 3.0.0



80
81
82
83
# File 'lib/bson/document.rb', line 80

def initialize(elements = nil)
  super()
  (elements || {}).each_pair{ |key, value| self[key] = value }
end

Instance Method Details

#[](key) ⇒ Object

Get a value from the document for the provided key. Can use string or symbol access, but the fastest will be to always provide a key that is of the same type as the stored keys.

Examples:

Get an element for the key.

document["field"]

Get an element for the key by symbol.

document[:field]

Parameters:

Returns:

  • (Object)

    The found value, or nil if none found.

Since:

  • 2.0.0



52
53
54
# File 'lib/bson/document.rb', line 52

def [](key)
  super(convert_key(key))
end

#[]=(key, value) ⇒ Object

Set a value on the document. Will normalize symbol keys into strings.

Examples:

Set a value on the document.

document[:test] = "value"

Parameters:

Returns:

  • (Object)

    The updated value.

Since:

  • 3.0.0



67
68
69
# File 'lib/bson/document.rb', line 67

def []=(key, value)
  super(convert_key(key), convert_value(value))
end

#merge(other, &block) ⇒ Object

Merge this document with another document, returning a new document in the process.

Examples:

Merge with another document.

document.merge(name: "Bob")

Parameters:

Since:

  • 3.0.0



96
97
98
# File 'lib/bson/document.rb', line 96

def merge(other, &block)
  dup.merge!(other, &block)
end

#merge!(other) ⇒ Object Also known as: update

Merge this document with another document, returning the same document in the process.

Examples:

Merge with another document.

document.merge(name: "Bob")

Parameters:

Since:

  • 3.0.0



111
112
113
114
115
116
117
# File 'lib/bson/document.rb', line 111

def merge!(other)
  other.each_pair do |key, value|
    value = yield(convert_key(key), self[key], convert_value(value)) if block_given?
    self[key] = value
  end
  self
end