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

NAME

6       BSON - BSON serialization and deserialization (EOL)
7

VERSION

9       version v1.12.2
10

END OF LIFE NOTICE

12       Version v1.12.0 was the final feature release of the MongoDB BSON
13       library and version v1.12.2 is the final patch release.
14
15       As of August 13, 2020, the MongoDB Perl driver and related libraries
16       have reached end of life and are no longer supported by MongoDB. See
17       the August 2019 deprecation notice
18       <https://www.mongodb.com/blog/post/the-mongodb-perl-driver-is-being-
19       deprecated> for rationale.
20
21       If members of the community wish to continue development, they are
22       welcome to fork the code under the terms of the Apache 2 license and
23       release it under a new namespace.  Specifications and test files for
24       MongoDB drivers and libraries are published in an open repository:
25       mongodb/specifications
26       <https://github.com/mongodb/specifications/tree/master/source>.
27

SYNOPSIS

29           use BSON;
30           use BSON::Types ':all';
31           use boolean;
32
33           my $codec = BSON->new;
34
35           my $document = {
36               _id             => bson_oid(),
37               creation_time   => bson_time(), # now
38               zip_code        => bson_string("08544"),
39               hidden          => false,
40           };
41
42           my $bson = $codec->encode_one( $document );
43           my $doc  = $codec->decode_one( $bson     );
44

DESCRIPTION

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

ATTRIBUTES

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

METHODS

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

FUNCTIONS

293   encode
294           my $bson = encode({ bar => 'foo' }, \%options);
295
296       This is the legacy, functional interface and is only exported on
297       demand.  It takes a hashref and returns a BSON string.  It uses an
298       internal codec singleton with default attributes.
299
300   decode
301           my $hash = decode( $bson, \%options );
302
303       This is the legacy, functional interface and is only exported on
304       demand.  It takes a BSON string and returns a hashref.  It uses an
305       internal codec singleton with default attributes.
306

PERL-BSON TYPE MAPPING

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

THREADS

428       Threads are never recommended in Perl, but this module is thread safe.
429

ENVIRONMENT

431       •   PERL_BSON_BACKEND – if set at compile time, this will be treated as
432           a module name.  The module will be loaded and used as the BSON
433           backend implementation.  It must implement the same API as
434           "BSON::PP".
435
436       •   BSON_EXTJSON - if set, serializing BSON type wrappers via "TO_JSON"
437           will produce Extended JSON v2 output.
438
439       •   BSON_EXTJSON_RELAXED - if producing Extended JSON output, if this
440           is true, values will use the "Relaxed" form of Extended JSON, which
441           sacrifices type round-tripping for improved human readability.
442

SEMANTIC VERSIONING SCHEME

444       Starting with BSON "v0.999.0", this module is using a "tick-tock"
445       three-part version-tuple numbering scheme: "vX.Y.Z"
446
447       •   In stable releases, "X" will be incremented for incompatible API
448           changes.
449
450       •   Even-value increments of "Y" indicate stable releases with new
451           functionality.  "Z" will be incremented for bug fixes.
452
453       •   Odd-value increments of "Y" indicate unstable ("development")
454           releases that should not be used in production.  "Z" increments
455           have no semantic meaning; they indicate only successive development
456           releases.  Development releases may have API-breaking changes,
457           usually indicated by "Y" equal to "999".
458

HISTORY AND ROADMAP

460       This module was originally written by Stefan G.  In 2014, he graciously
461       transferred ongoing maintenance to MongoDB, Inc.
462
463       The "bson_xxxx" helper functions in BSON::Types were inspired by
464       similar work in Mango::BSON by Sebastian Riedel.
465

AUTHORS

467       •   David Golden <david@mongodb.com>
468
469       •   Stefan G. <minimalist@lavabit.com>
470

CONTRIBUTORS

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