1BSON(3)               User Contributed Perl Documentation              BSON(3)
2
3
4

NAME

6       BSON - BSON serialization and deserialization
7

VERSION

9       version v1.12.1
10

END OF LIFE NOTICE

12       Version v1.12.0 is the final feature release of the MongoDB BSON
13       library.  The library is now in a 12-month "sunset" period and will
14       receive security patches and critical bug fixes only.  The BSON library
15       will be end-of-life and unsupported on August 13, 2020.
16

SYNOPSIS

18           use BSON;
19           use BSON::Types ':all';
20           use boolean;
21
22           my $codec = BSON->new;
23
24           my $document = {
25               _id             => bson_oid(),
26               creation_time   => bson_time(), # now
27               zip_code        => bson_string("08544"),
28               hidden          => false,
29           };
30
31           my $bson = $codec->encode_one( $document );
32           my $doc  = $codec->decode_one( $bson     );
33

DESCRIPTION

35       This class implements a BSON encoder/decoder ("codec").  It consumes
36       "documents" (typically hash references) and emits BSON strings and vice
37       versa in accordance with the BSON Specification <http://bsonspec.org>.
38
39       BSON is the primary data representation for MongoDB.  While this module
40       has several features that support MongoDB-specific needs and
41       conventions, it can be used as a standalone serialization format.
42
43       The codec may be customized through attributes on the codec option as
44       well as encode/decode specific options on methods:
45
46           my $codec = BSON->new( \%global_attributes );
47
48           my $bson = $codec->encode_one( $document, \%encode_options );
49           my $doc  = $codec->decode_one( $bson    , \%decode_options );
50
51       Because BSON is strongly-typed and Perl is not, this module supports a
52       number of "type wrappers" – classes that wrap Perl data to indicate how
53       they should serialize. The BSON::Types module describes these and
54       provides associated helper functions.  See "PERL-BSON TYPE MAPPING" for
55       more details.
56
57       When decoding, type wrappers are used for any data that has no native
58       Perl representation.  Optionally, all data may be wrapped for precise
59       control of round-trip encoding.
60
61       Please read the configuration attributes carefully to understand more
62       about how to control encoding and decoding.
63
64       At compile time, this module will select an implementation backend.  It
65       will prefer "BSON::XS" (released separately) if available, or will fall
66       back to BSON::PP (bundled with this module).  See "ENVIRONMENT" for a
67       way to control the selection of the backend.
68

ATTRIBUTES

70   error_callback
71       This attribute specifies a function reference that will be called with
72       three positional arguments:
73
74       ·   an error string argument describing the error condition
75
76       ·   a reference to the problematic document or byte-string
77
78       ·   the method in which the error occurred (e.g. "encode_one" or
79           "decode_one")
80
81       Note: for decoding errors, the byte-string is passed as a reference to
82       avoid copying possibly large strings.
83
84       If not provided, errors messages will be thrown with "Carp::croak".
85
86   invalid_chars
87       A string containing ASCII characters that must not appear in keys.  The
88       default is the empty string, meaning there are no invalid characters.
89
90   max_length
91       This attribute defines the maximum document size. The default is 0,
92       which disables any maximum.
93
94       If set to a positive number, it applies to both encoding and decoding
95       (the latter is necessary for prevention of resource consumption
96       attacks).
97
98   op_char
99       This is a single character to use for special MongoDB-specific query
100       operators.  If a key starts with "op_char", the "op_char" character
101       will be replaced with "$".
102
103       The default is "$", meaning that no replacement is necessary.
104
105   ordered
106       If set to a true value, then decoding will return a reference to a tied
107       hash that preserves key order. Otherwise, a regular (unordered) hash
108       reference will be returned.
109
110       IMPORTANT CAVEATS:
111
112       ·   When 'ordered' is true, users must not rely on the return value
113           being any particular tied hash implementation.  It may change in
114           the future for efficiency.
115
116       ·   Turning this option on entails a significant speed penalty as tied
117           hashes are slower than regular Perl hashes.
118
119       The default is false.
120
121   prefer_numeric
122       When false, scalar values will be encoded as a number if they were
123       originally a number or were ever used in a numeric context.  However, a
124       string that looks like a number but was never used in a numeric context
125       (e.g. "42") will be encoded as a string.
126
127       If "prefer_numeric" is set to true, the encoder will attempt to coerce
128       strings that look like a number into a numeric value.  If the string
129       doesn't look like a double or integer, it will be encoded as a string.
130
131       IMPORTANT CAVEAT: the heuristics for determining whether something is a
132       string or number are less accurate on older Perls.  See BSON::Types for
133       wrapper classes that specify exact serialization types.
134
135       The default is false.
136
137   wrap_dbrefs
138       If set to true, during decoding, documents with the fields '$id' and
139       '$ref' (literal dollar signs, not variables) will be wrapped as
140       BSON::DBRef objects.  If false, they are decoded into ordinary hash
141       references (or ordered hashes, if "ordered" is true).
142
143       The default is true.
144
145   wrap_numbers
146       If set to true, during decoding, numeric values will be wrapped into
147       BSON type-wrappers: BSON::Double, BSON::Int64 or BSON::Int32.  While
148       very slow, this can help ensure fields can round-trip if unmodified.
149
150       The default is false.
151
152   wrap_strings
153       If set to true, during decoding, string values will be wrapped into a
154       BSON type-wrappers, BSON::String.  While very slow, this can help
155       ensure fields can round-trip if unmodified.
156
157       The default is false.
158
159   dt_type (Discouraged)
160       Sets the type of object which is returned for BSON DateTime fields. The
161       default is "undef", which returns objects of type BSON::Time.  This is
162       overloaded to be the integer epoch value when used as a number or
163       string, so is somewhat backwards compatible with "dt_type" in the
164       MongoDB driver.
165
166       Other acceptable values are BSON::Time (explicitly), DateTime,
167       Time::Moment, DateTime::Tiny, Mango::BSON::Time.
168
169       Because BSON::Time objects have methods to convert to DateTime,
170       Time::Moment or DateTime::Tiny, use of this field is discouraged.
171       Users should use these methods on demand.  This option is provided for
172       backwards compatibility only.
173

METHODS

175   encode_one
176           $byte_string = $codec->encode_one( $doc );
177           $byte_string = $codec->encode_one( $doc, \%options );
178
179       Takes a "document", typically a hash reference, an array reference, or
180       a Tie::IxHash object and returns a byte string with the BSON
181       representation of the document.
182
183       An optional hash reference of options may be provided.  Valid options
184       include:
185
186       ·   first_key – if "first_key" is defined, it and "first_value" will be
187           encoded first in the output BSON; any matching key found in the
188           document will be ignored.
189
190       ·   first_value - value to assign to "first_key"; will encode as Null
191           if omitted
192
193       ·   error_callback – overrides codec default
194
195       ·   invalid_chars – overrides codec default
196
197       ·   max_length – overrides codec default
198
199       ·   op_char – overrides codec default
200
201       ·   prefer_numeric – overrides codec default
202
203   decode_one
204           $doc = $codec->decode_one( $byte_string );
205           $doc = $codec->decode_one( $byte_string, \%options );
206
207       Takes a byte string with a BSON-encoded document and returns a hash
208       reference representing the decoded document.
209
210       An optional hash reference of options may be provided.  Valid options
211       include:
212
213       ·   dt_type – overrides codec default
214
215       ·   error_callback – overrides codec default
216
217       ·   max_length – overrides codec default
218
219       ·   ordered - overrides codec default
220
221       ·   wrap_dbrefs - overrides codec default
222
223       ·   wrap_numbers - overrides codec default
224
225       ·   wrap_strings - overrides codec default
226
227   clone
228           $copy = $codec->clone( ordered => 1 );
229
230       Constructs a copy of the original codec, but allows changing attributes
231       in the copy.
232
233   create_oid
234           $oid = BSON->create_oid;
235
236       This class method returns a new BSON::OID.  This abstracts OID
237       generation away from any specific Object ID class and makes it an
238       interface on a BSON codec.  Alternative BSON codecs should define a
239       similar class method that returns an Object ID of whatever type is
240       appropriate.
241
242   inflate_extjson (DEPRECATED)
243       This legacy method does not follow the MongoDB Extended JSON
244       <https://github.com/mongodb/specifications/blob/master/source/extended-
245       json.rst> specification.
246
247       Use "extjson_to_perl" instead.
248
249   perl_to_extjson
250           use JSON::MaybeXS;
251           my $ext = BSON->perl_to_extjson($data, \%options);
252           my $json = encode_json($ext);
253
254       Takes a perl data structure (i.e. hashref) and turns it into an MongoDB
255       Extended JSON
256       <https://github.com/mongodb/specifications/blob/master/source/extended-
257       json.rst> structure. Note that the structure will still have to be
258       serialized.
259
260       Possible options are:
261
262       ·   "relaxed" A boolean indicating if "relaxed extended JSON" should
263
264           be generated. If not set, the default value is taken from the
265           "BSON_EXTJSON_RELAXED" environment variable.
266
267   extjson_to_perl
268           use JSON::MaybeXS;
269           my $ext = decode_json($json);
270           my $data = $bson->extjson_to_perl($ext);
271
272       Takes an MongoDB Extended JSON
273       <https://github.com/mongodb/specifications/blob/master/source/extended-
274       json.rst> data structure and inflates it into a Perl data structure.
275       Note that you have to decode the JSON string manually beforehand.
276
277       Canonically specified numerical values like "{"$numberInt":"23"}" will
278       be inflated into their respective "BSON::*" wrapper types. Plain
279       numeric values will be left as-is.
280

FUNCTIONS

282   encode
283           my $bson = encode({ bar => 'foo' }, \%options);
284
285       This is the legacy, functional interface and is only exported on
286       demand.  It takes a hashref and returns a BSON string.  It uses an
287       internal codec singleton with default attributes.
288
289   decode
290           my $hash = decode( $bson, \%options );
291
292       This is the legacy, functional interface and is only exported on
293       demand.  It takes a BSON string and returns a hashref.  It uses an
294       internal codec singleton with default attributes.
295

PERL-BSON TYPE MAPPING

297       BSON has numerous data types and Perl does not.
298
299       When decoding, each BSON type should result in a single, predictable
300       Perl type.  Where no native Perl type is appropriate, BSON decodes to
301       an object of a particular class (a "type wrapper").
302
303       When encoding, for historical reasons, there may be many Perl
304       representations that should encode to a particular BSON type.  For
305       example, all the popular "boolean" type modules on CPAN should encode
306       to the BSON boolean type.  Likewise, as this module is intended to
307       supersede the type wrappers that have shipped with the MongoDB module,
308       those type wrapper are supported by this codec.
309
310       The table below describes the BSON/Perl mapping for both encoding and
311       decoding.
312
313       On the left are all the Perl types or classes this BSON codec knows how
314       to serialize to BSON.  The middle column is the BSON type for each
315       class.  The right-most column is the Perl type or class that the BSON
316       type deserializes to.  Footnotes indicate variations or special
317       behaviors.
318
319           Perl type/class ->          BSON type        -> Perl type/class
320           -------------------------------------------------------------------
321           float[1]                    0x01 DOUBLE         float[2]
322           BSON::Double
323           -------------------------------------------------------------------
324           string[3]                   0x02 UTF8           string[2]
325           BSON::String
326           -------------------------------------------------------------------
327           hashref                     0x03 DOCUMENT       hashref[4][5]
328           BSON::Doc
329           BSON::Raw
330           MongoDB::BSON::Raw[d]
331           Tie::IxHash
332           -------------------------------------------------------------------
333           arrayref                    0x04 ARRAY          arrayref
334           -------------------------------------------------------------------
335           BSON::Bytes                 0x05 BINARY         BSON::Bytes
336           scalarref
337           BSON::Binary[d]
338           MongoDB::BSON::Binary[d]
339           -------------------------------------------------------------------
340           n/a                         0x06 UNDEFINED[d]   undef
341           -------------------------------------------------------------------
342           BSON::OID                   0x07 OID            BSON::OID
343           BSON::ObjectId[d]
344           MongoDB::OID[d]
345           -------------------------------------------------------------------
346           boolean                     0x08 BOOL           boolean
347           BSON::Bool[d]
348           JSON::XS::Boolean
349           JSON::PP::Boolean
350           JSON::Tiny::_Bool
351           Mojo::JSON::_Bool
352           Cpanel::JSON::XS::Boolean
353           Types::Serialiser::Boolean
354           -------------------------------------------------------------------
355           BSON::Time                  0x09 DATE_TIME      BSON::Time
356           DateTime
357           DateTime::Tiny
358           Time::Moment
359           Mango::BSON::Time
360           -------------------------------------------------------------------
361           undef                       0x0a NULL           undef
362           -------------------------------------------------------------------
363           BSON::Regex                 0x0b REGEX          BSON::Regex
364           qr// reference
365           MongoDB::BSON::Regexp[d]
366           -------------------------------------------------------------------
367           n/a                         0x0c DBPOINTER[d]   BSON::DBRef
368           -------------------------------------------------------------------
369           BSON::Code[6]               0x0d CODE           BSON::Code
370           MongoDB::Code[6]
371           -------------------------------------------------------------------
372           n/a                         0x0e SYMBOL[d]      string
373           -------------------------------------------------------------------
374           BSON::Code[6]               0x0f CODEWSCOPE     BSON::Code
375           MongoDB::Code[6]
376           -------------------------------------------------------------------
377           integer[7][8]               0x10 INT32          integer[2]
378           BSON::Int32
379           -------------------------------------------------------------------
380           BSON::Timestamp             0x11 TIMESTAMP      BSON::Timestamp
381           MongoDB::Timestamp[d]
382           -------------------------------------------------------------------
383           integer[7]                  0x12 INT64          integer[2][9]
384           BSON::Int64
385           Math::BigInt
386           Math::Int64
387           -------------------------------------------------------------------
388           BSON::MaxKey                0x7F MAXKEY         BSON::MaxKey
389           MongoDB::MaxKey[d]
390           -------------------------------------------------------------------
391           BSON::MinKey                0xFF MINKEY         BSON::MinKey
392           MongoDB::MinKey[d]
393
394           [d] Deprecated or soon to be deprecated.
395           [1] Scalar with "NV" internal representation or a string that looks
396               like a float if the 'prefer_numeric' option is true.
397           [2] If the 'wrap_numbers' option is true, numeric types will be wrapped
398               as BSON::Double, BSON::Int32 or BSON::Int64 as appropriate to ensure
399               round-tripping. If the 'wrap_strings' option is true, strings will
400               be wrapped as BSON::String, likewise.
401           [3] Scalar without "NV" or "IV" representation and not identified as a
402               number by notes [1] or [7].
403           [4] If 'ordered' option is set, will return a tied hash that preserves
404               order (deprecated 'ixhash' option still works).
405           [5] If the document appears to contain a DBRef and a 'dbref_callback'
406               exists, that callback is executed with the deserialized document.
407           [6] Code is serialized as CODE or CODEWSCOPE depending on whether a
408               scope hashref exists in BSON::Code/MongoDB::Code.
409           [7] Scalar with "IV" internal representation or a string that looks like
410               an integer if the 'prefer_numeric' option is true.
411           [8] Only if the integer fits in 32 bits.
412           [9] On 32-bit platforms, 64-bit integers are deserialized to
413               Math::BigInt objects (even if subsequently wrapped into
414               BSON::Int64 if 'wrap_scalars' is true).
415

THREADS

417       Threads are never recommended in Perl, but this module is thread safe.
418

ENVIRONMENT

420       ·   PERL_BSON_BACKEND – if set at compile time, this will be treated as
421           a module name.  The module will be loaded and used as the BSON
422           backend implementation.  It must implement the same API as
423           "BSON::PP".
424
425       ·   BSON_EXTJSON - if set, serializing BSON type wrappers via "TO_JSON"
426           will produce Extended JSON v2 output.
427
428       ·   BSON_EXTJSON_RELAXED - if producing Extended JSON output, if this
429           is true, values will use the "Relaxed" form of Extended JSON, which
430           sacrifices type round-tripping for improved human readability.
431

SEMANTIC VERSIONING SCHEME

433       Starting with BSON "v0.999.0", this module is using a "tick-tock"
434       three-part version-tuple numbering scheme: "vX.Y.Z"
435
436       ·   In stable releases, "X" will be incremented for incompatible API
437           changes.
438
439       ·   Even-value increments of "Y" indicate stable releases with new
440           functionality.  "Z" will be incremented for bug fixes.
441
442       ·   Odd-value increments of "Y" indicate unstable ("development")
443           releases that should not be used in production.  "Z" increments
444           have no semantic meaning; they indicate only successive development
445           releases.  Development releases may have API-breaking changes,
446           usually indicated by "Y" equal to "999".
447

HISTORY AND ROADMAP

449       This module was originally written by Stefan G.  In 2014, he graciously
450       transferred ongoing maintenance to MongoDB, Inc.
451
452       The "bson_xxxx" helper functions in BSON::Types were inspired by
453       similar work in Mango::BSON by Sebastian Riedel.
454

SUPPORT

456   Bugs / Feature Requests
457       Please report any bugs or feature requests through the issue tracker at
458       <https://jira.mongodb.org/browse/PERL>.  You will be notified
459       automatically of any progress on your issue.
460
461   Source Code
462       This is open source software.  The code repository is available for
463       public review and contribution under the terms of the license.
464
465       <https://github.com/mongodb/mongo-perl-bson>
466
467         git clone https://github.com/mongodb/mongo-perl-bson.git
468

AUTHORS

470       ·   David Golden <david@mongodb.com>
471
472       ·   Stefan G. <minimalist@lavabit.com>
473

CONTRIBUTORS

475       ·   Eric Daniels <eric.daniels@mongodb.com>
476
477       ·   Finn <toyou1995@gmail.com>
478
479       ·   Olivier Duclos <odc@cpan.org>
480
481       ·   Pat Gunn <pgunn@mongodb.com>
482
483       ·   Petr Písař <ppisar@redhat.com>
484
485       ·   Robert Sedlacek <rs@474.at>
486
487       ·   Thomas Bloor <tbsliver@shadow.cat>
488
489       ·   Tobias Leich <email@froggs.de>
490
491       ·   Wallace Reis <wallace@reis.me>
492
493       ·   Yury Zavarin <yury.zavarin@gmail.com>
494
495       ·   Oleg Kostyuk <cub@cpan.org>
496
498       This software is Copyright (c) 2019 by Stefan G. and MongoDB, Inc.
499
500       This is free software, licensed under:
501
502         The Apache License, Version 2.0, January 2004
503
504
505
506perl v5.30.0                      2019-08-14                           BSON(3)
Impressum