@@ -11,7 +11,7 @@ BSON 4.x Tutorial
1111.. contents:: On this page
1212 :local:
1313 :backlinks: none
14- :depth: 1
14+ :depth: 2
1515 :class: twocols
1616
1717This tutorial discusses using the Ruby BSON library.
@@ -409,6 +409,20 @@ access to them with symbol keys.
409409 BSON::Document[:key, "value"]
410410 BSON::Document.new
411411
412+ .. note::
413+
414+ All BSON documents are deserialized into instances of BSON::Document,
415+ even when the invocation is made from the ``Hash`` class:
416+
417+ .. code-block:: ruby
418+
419+ bson = {test: 1}.to_bson.to_s
420+ loaded = Hash.from_bson(BSON::ByteBuffer.new(bson))
421+ => {"test"=>1}
422+ loaded.class
423+ => BSON::Document
424+
425+
412426``BSON::MaxKey``
413427````````````````
414428
@@ -659,3 +673,40 @@ object, one must call ``compile`` on the returned object.
659673 regex.pattern #=> Returns the pattern as a string.
660674 regex.options #=> Returns the raw options as a String.
661675 regex.compile #=> Returns the compiled Ruby Regexp object.
676+
677+
678+ Key Order
679+ ---------
680+
681+ BSON documents preserve the order of keys, because the documents are stored
682+ as lists of key-value pairs. Hashes in Ruby also preserve key order; thus
683+ the order of keys specified in Ruby will be respected when serializing a
684+ hash to a BSON document, and when deserializing a BSON document into a hash
685+ the order of keys in the document will match the order of keys in the hash.
686+
687+
688+ Duplicate Keys
689+ --------------
690+
691+ BSON specification allows BSON documents to have duplicate keys, because the
692+ documents are stored as lists of key-value pairs. Applications should refrain
693+ from generating such documents, because MongoDB server behavior is undefined
694+ when a BSON document contains duplicate keys.
695+
696+ Since in Ruby hashes cannot have duplicate keys, when serializing Ruby hashes
697+ to BSON documents no duplicate keys will be generated. (It is still possible
698+ to hand-craft a BSON document that would have duplicate keys in Ruby, and
699+ some of the other MongoDB BSON libraries may permit creating BSON documents
700+ with duplicate keys.)
701+
702+ Note that, since keys in BSON documents are always stored as strings,
703+ specifying the same key as as string and a symbol in Ruby only retains the
704+ most recent specification:
705+
706+ .. code-block:: ruby
707+
708+ BSON::Document.new(test: 1, 'test' => 2)
709+ => {"test"=>2}
710+
711+ When loading a BSON document with duplicate keys, the last value for a
712+ duplicated key overwrites previous values for the same key.
0 commit comments