1BSON(3) User Contributed Perl Documentation BSON(3)
2
3
4
6 BSON - BSON serialization and deserialization
7
9 version v1.10.2
10
12 use BSON;
13 use BSON::Types ':all';
14 use boolean;
15
16 my $codec = BSON->new;
17
18 my $document = {
19 _id => bson_oid(),
20 creation_time => bson_time(), # now
21 zip_code => bson_string("08544"),
22 hidden => false,
23 };
24
25 my $bson = $codec->encode_one( $document );
26 my $doc = $codec->decode_one( $bson );
27
29 This class implements a BSON encoder/decoder ("codec"). It consumes
30 "documents" (typically hash references) and emits BSON strings and vice
31 versa in accordance with the BSON Specification <http://bsonspec.org>.
32
33 BSON is the primary data representation for MongoDB. While this module
34 has several features that support MongoDB-specific needs and
35 conventions, it can be used as a standalone serialization format.
36
37 The codec may be customized through attributes on the codec option as
38 well as encode/decode specific options on methods:
39
40 my $codec = BSON->new( \%global_attributes );
41
42 my $bson = $codec->encode_one( $document, \%encode_options );
43 my $doc = $codec->decode_one( $bson , \%decode_options );
44
45 Because BSON is strongly-typed and Perl is not, this module supports a
46 number of "type wrappers" – classes that wrap Perl data to indicate how
47 they should serialize. The BSON::Types module describes these and
48 provides associated helper functions. See "PERL-BSON TYPE MAPPING" for
49 more details.
50
51 When decoding, type wrappers are used for any data that has no native
52 Perl representation. Optionally, all data may be wrapped for precise
53 control of round-trip encoding.
54
55 Please read the configuration attributes carefully to understand more
56 about how to control encoding and decoding.
57
58 At compile time, this module will select an implementation backend. It
59 will prefer "BSON::XS" (released separately) if available, or will fall
60 back to BSON::PP (bundled with this module). See "ENVIRONMENT" for a
61 way to control the selection of the backend.
62
64 error_callback
65 This attribute specifies a function reference that will be called with
66 three positional arguments:
67
68 · an error string argument describing the error condition
69
70 · a reference to the problematic document or byte-string
71
72 · the method in which the error occurred (e.g. "encode_one" or
73 "decode_one")
74
75 Note: for decoding errors, the byte-string is passed as a reference to
76 avoid copying possibly large strings.
77
78 If not provided, errors messages will be thrown with "Carp::croak".
79
80 invalid_chars
81 A string containing ASCII characters that must not appear in keys. The
82 default is the empty string, meaning there are no invalid characters.
83
84 max_length
85 This attribute defines the maximum document size. The default is 0,
86 which disables any maximum.
87
88 If set to a positive number, it applies to both encoding and decoding
89 (the latter is necessary for prevention of resource consumption
90 attacks).
91
92 op_char
93 This is a single character to use for special MongoDB-specific query
94 operators. If a key starts with "op_char", the "op_char" character
95 will be replaced with "$".
96
97 The default is "$", meaning that no replacement is necessary.
98
99 ordered
100 If set to a true value, then decoding will return a reference to a tied
101 hash that preserves key order. Otherwise, a regular (unordered) hash
102 reference will be returned.
103
104 IMPORTANT CAVEATS:
105
106 · When 'ordered' is true, users must not rely on the return value
107 being any particular tied hash implementation. It may change in
108 the future for efficiency.
109
110 · Turning this option on entails a significant speed penalty as tied
111 hashes are slower than regular Perl hashes.
112
113 The default is false.
114
115 prefer_numeric
116 When false, scalar values will be encoded as a number if they were
117 originally a number or were ever used in a numeric context. However, a
118 string that looks like a number but was never used in a numeric context
119 (e.g. "42") will be encoded as a string.
120
121 If "prefer_numeric" is set to true, the encoder will attempt to coerce
122 strings that look like a number into a numeric value. If the string
123 doesn't look like a double or integer, it will be encoded as a string.
124
125 IMPORTANT CAVEAT: the heuristics for determining whether something is a
126 string or number are less accurate on older Perls. See BSON::Types for
127 wrapper classes that specify exact serialization types.
128
129 The default is false.
130
131 wrap_dbrefs
132 If set to true, during decoding, documents with the fields '$id' and
133 '$ref' (literal dollar signs, not variables) will be wrapped as
134 BSON::DBRef objects. If false, they are decoded into ordinary hash
135 references (or ordered hashes, if "ordered" is true).
136
137 The default is true.
138
139 wrap_numbers
140 If set to true, during decoding, numeric values will be wrapped into
141 BSON type-wrappers: BSON::Double, BSON::Int64 or BSON::Int32. While
142 very slow, this can help ensure fields can round-trip if unmodified.
143
144 The default is false.
145
146 wrap_strings
147 If set to true, during decoding, string values will be wrapped into a
148 BSON type-wrappers, BSON::String. While very slow, this can help
149 ensure fields can round-trip if unmodified.
150
151 The default is false.
152
153 dt_type (Discouraged)
154 Sets the type of object which is returned for BSON DateTime fields. The
155 default is "undef", which returns objects of type BSON::Time. This is
156 overloaded to be the integer epoch value when used as a number or
157 string, so is somewhat backwards compatible with "dt_type" in the
158 MongoDB driver.
159
160 Other acceptable values are BSON::Time (explicitly), DateTime,
161 Time::Moment, DateTime::Tiny, Mango::BSON::Time.
162
163 Because BSON::Time objects have methods to convert to DateTime,
164 Time::Moment or DateTime::Tiny, use of this field is discouraged.
165 Users should use these methods on demand. This option is provided for
166 backwards compatibility only.
167
169 encode_one
170 $byte_string = $codec->encode_one( $doc );
171 $byte_string = $codec->encode_one( $doc, \%options );
172
173 Takes a "document", typically a hash reference, an array reference, or
174 a Tie::IxHash object and returns a byte string with the BSON
175 representation of the document.
176
177 An optional hash reference of options may be provided. Valid options
178 include:
179
180 · first_key – if "first_key" is defined, it and "first_value" will be
181 encoded first in the output BSON; any matching key found in the
182 document will be ignored.
183
184 · first_value - value to assign to "first_key"; will encode as Null
185 if omitted
186
187 · error_callback – overrides codec default
188
189 · invalid_chars – overrides codec default
190
191 · max_length – overrides codec default
192
193 · op_char – overrides codec default
194
195 · prefer_numeric – overrides codec default
196
197 decode_one
198 $doc = $codec->decode_one( $byte_string );
199 $doc = $codec->decode_one( $byte_string, \%options );
200
201 Takes a byte string with a BSON-encoded document and returns a hash
202 reference representing the decoded document.
203
204 An optional hash reference of options may be provided. Valid options
205 include:
206
207 · dt_type – overrides codec default
208
209 · error_callback – overrides codec default
210
211 · max_length – overrides codec default
212
213 · ordered - overrides codec default
214
215 · wrap_dbrefs - overrides codec default
216
217 · wrap_numbers - overrides codec default
218
219 · wrap_strings - overrides codec default
220
221 clone
222 $copy = $codec->clone( ordered => 1 );
223
224 Constructs a copy of the original codec, but allows changing attributes
225 in the copy.
226
227 create_oid
228 $oid = BSON->create_oid;
229
230 This class method returns a new BSON::OID. This abstracts OID
231 generation away from any specific Object ID class and makes it an
232 interface on a BSON codec. Alternative BSON codecs should define a
233 similar class method that returns an Object ID of whatever type is
234 appropriate.
235
236 inflate_extjson (DEPRECATED)
237 This legacy method does not follow the MongoDB Extended JSON
238 <https://github.com/mongodb/specifications/blob/master/source/extended-
239 json.rst> specification.
240
241 Use "extjson_to_perl" instead.
242
243 perl_to_extjson
244 use JSON::MaybeXS;
245 my $ext = BSON->perl_to_extjson($data, \%options);
246 my $json = encode_json($ext);
247
248 Takes a perl data structure (i.e. hashref) and turns it into an MongoDB
249 Extended JSON
250 <https://github.com/mongodb/specifications/blob/master/source/extended-
251 json.rst> structure. Note that the structure will still have to be
252 serialized.
253
254 Possible options are:
255
256 · "relaxed" A boolean indicating if "relaxed extended JSON" should
257
258 be generated. If not set, the default value is taken from the
259 "BSON_EXTJSON_RELAXED" environment variable.
260
261 extjson_to_perl
262 use JSON::MaybeXS;
263 my $ext = decode_json($json);
264 my $data = $bson->extjson_to_perl($ext);
265
266 Takes an MongoDB Extended JSON
267 <https://github.com/mongodb/specifications/blob/master/source/extended-
268 json.rst> data structure and inflates it into a Perl data structure.
269 Note that you have to decode the JSON string manually beforehand.
270
271 Canonically specified numerical values like "{"$numberInt":"23"}" will
272 be inflated into their respective "BSON::*" wrapper types. Plain
273 numeric values will be left as-is.
274
276 encode
277 my $bson = encode({ bar => 'foo' }, \%options);
278
279 This is the legacy, functional interface and is only exported on
280 demand. It takes a hashref and returns a BSON string. It uses an
281 internal codec singleton with default attributes.
282
283 decode
284 my $hash = decode( $bson, \%options );
285
286 This is the legacy, functional interface and is only exported on
287 demand. It takes a BSON string and returns a hashref. It uses an
288 internal codec singleton with default attributes.
289
291 BSON has numerous data types and Perl does not.
292
293 When decoding, each BSON type should result in a single, predictable
294 Perl type. Where no native Perl type is appropriate, BSON decodes to
295 an object of a particular class (a "type wrapper").
296
297 When encoding, for historical reasons, there may be many Perl
298 representations that should encode to a particular BSON type. For
299 example, all the popular "boolean" type modules on CPAN should encode
300 to the BSON boolean type. Likewise, as this module is intended to
301 supersede the type wrappers that have shipped with the MongoDB module,
302 those type wrapper are supported by this codec.
303
304 The table below describes the BSON/Perl mapping for both encoding and
305 decoding.
306
307 On the left are all the Perl types or classes this BSON codec knows how
308 to serialize to BSON. The middle column is the BSON type for each
309 class. The right-most column is the Perl type or class that the BSON
310 type deserializes to. Footnotes indicate variations or special
311 behaviors.
312
313 Perl type/class -> BSON type -> Perl type/class
314 -------------------------------------------------------------------
315 float[1] 0x01 DOUBLE float[2]
316 BSON::Double
317 -------------------------------------------------------------------
318 string[3] 0x02 UTF8 string[2]
319 BSON::String
320 -------------------------------------------------------------------
321 hashref 0x03 DOCUMENT hashref[4][5]
322 BSON::Doc
323 BSON::Raw
324 MongoDB::BSON::Raw[d]
325 Tie::IxHash
326 -------------------------------------------------------------------
327 arrayref 0x04 ARRAY arrayref
328 -------------------------------------------------------------------
329 BSON::Bytes 0x05 BINARY BSON::Bytes
330 scalarref
331 BSON::Binary[d]
332 MongoDB::BSON::Binary[d]
333 -------------------------------------------------------------------
334 n/a 0x06 UNDEFINED[d] undef
335 -------------------------------------------------------------------
336 BSON::OID 0x07 OID BSON::OID
337 BSON::ObjectId[d]
338 MongoDB::OID[d]
339 -------------------------------------------------------------------
340 boolean 0x08 BOOL boolean
341 BSON::Bool[d]
342 JSON::XS::Boolean
343 JSON::PP::Boolean
344 JSON::Tiny::_Bool
345 Mojo::JSON::_Bool
346 Cpanel::JSON::XS::Boolean
347 Types::Serialiser::Boolean
348 -------------------------------------------------------------------
349 BSON::Time 0x09 DATE_TIME BSON::Time
350 DateTime
351 DateTime::Tiny
352 Time::Moment
353 Mango::BSON::Time
354 -------------------------------------------------------------------
355 undef 0x0a NULL undef
356 -------------------------------------------------------------------
357 BSON::Regex 0x0b REGEX BSON::Regex
358 qr// reference
359 MongoDB::BSON::Regexp[d]
360 -------------------------------------------------------------------
361 n/a 0x0c DBPOINTER[d] BSON::DBRef
362 -------------------------------------------------------------------
363 BSON::Code[6] 0x0d CODE BSON::Code
364 MongoDB::Code[6]
365 -------------------------------------------------------------------
366 n/a 0x0e SYMBOL[d] string
367 -------------------------------------------------------------------
368 BSON::Code[6] 0x0f CODEWSCOPE BSON::Code
369 MongoDB::Code[6]
370 -------------------------------------------------------------------
371 integer[7][8] 0x10 INT32 integer[2]
372 BSON::Int32
373 -------------------------------------------------------------------
374 BSON::Timestamp 0x11 TIMESTAMP BSON::Timestamp
375 MongoDB::Timestamp[d]
376 -------------------------------------------------------------------
377 integer[7] 0x12 INT64 integer[2][9]
378 BSON::Int64
379 Math::BigInt
380 Math::Int64
381 -------------------------------------------------------------------
382 BSON::MaxKey 0x7F MAXKEY BSON::MaxKey
383 MongoDB::MaxKey[d]
384 -------------------------------------------------------------------
385 BSON::MinKey 0xFF MINKEY BSON::MinKey
386 MongoDB::MinKey[d]
387
388 [d] Deprecated or soon to be deprecated.
389 [1] Scalar with "NV" internal representation or a string that looks
390 like a float if the 'prefer_numeric' option is true.
391 [2] If the 'wrap_numbers' option is true, numeric types will be wrapped
392 as BSON::Double, BSON::Int32 or BSON::Int64 as appropriate to ensure
393 round-tripping. If the 'wrap_strings' option is true, strings will
394 be wrapped as BSON::String, likewise.
395 [3] Scalar without "NV" or "IV" representation and not identified as a
396 number by notes [1] or [7].
397 [4] If 'ordered' option is set, will return a tied hash that preserves
398 order (deprecated 'ixhash' option still works).
399 [5] If the document appears to contain a DBRef and a 'dbref_callback'
400 exists, that callback is executed with the deserialized document.
401 [6] Code is serialized as CODE or CODEWSCOPE depending on whether a
402 scope hashref exists in BSON::Code/MongoDB::Code.
403 [7] Scalar with "IV" internal representation or a string that looks like
404 an integer if the 'prefer_numeric' option is true.
405 [8] Only if the integer fits in 32 bits.
406 [9] On 32-bit platforms, 64-bit integers are deserialized to
407 Math::BigInt objects (even if subsequently wrapped into
408 BSON::Int64 if 'wrap_scalars' is true).
409
411 Threads are never recommended in Perl, but this module is thread safe.
412
414 · PERL_BSON_BACKEND – if set at compile time, this will be treated as
415 a module name. The module will be loaded and used as the BSON
416 backend implementation. It must implement the same API as
417 "BSON::PP".
418
419 · BSON_EXTJSON - if set, serializing BSON type wrappers via "TO_JSON"
420 will produce Extended JSON v2 output.
421
422 · BSON_EXTJSON_RELAXED - if producing Extended JSON output, if this
423 is true, values will use the "Relaxed" form of Extended JSON, which
424 sacrifices type round-tripping for improved human readability.
425
427 Starting with BSON "v0.999.0", this module is using a "tick-tock"
428 three-part version-tuple numbering scheme: "vX.Y.Z"
429
430 · In stable releases, "X" will be incremented for incompatible API
431 changes.
432
433 · Even-value increments of "Y" indicate stable releases with new
434 functionality. "Z" will be incremented for bug fixes.
435
436 · Odd-value increments of "Y" indicate unstable ("development")
437 releases that should not be used in production. "Z" increments
438 have no semantic meaning; they indicate only successive development
439 releases. Development releases may have API-breaking changes,
440 usually indicated by "Y" equal to "999".
441
443 This module was originally written by Stefan G. In 2014, he graciously
444 transferred ongoing maintenance to MongoDB, Inc.
445
446 The "bson_xxxx" helper functions in BSON::Types were inspired by
447 similar work in Mango::BSON by Sebastian Riedel.
448
450 Bugs / Feature Requests
451 Please report any bugs or feature requests through the issue tracker at
452 <https://jira.mongodb.org/browse/PERL>. You will be notified
453 automatically of any progress on your issue.
454
455 Source Code
456 This is open source software. The code repository is available for
457 public review and contribution under the terms of the license.
458
459 <https://github.com/mongodb/mongo-perl-bson>
460
461 git clone https://github.com/mongodb/mongo-perl-bson.git
462
464 · David Golden <david@mongodb.com>
465
466 · Stefan G. <minimalist@lavabit.com>
467
469 · Eric Daniels <eric.daniels@mongodb.com>
470
471 · Finn <toyou1995@gmail.com>
472
473 · Olivier Duclos <odc@cpan.org>
474
475 · Pat Gunn <pgunn@mongodb.com>
476
477 · Petr Písař <ppisar@redhat.com>
478
479 · Robert Sedlacek <rs@474.at>
480
481 · Thomas Bloor <tbsliver@shadow.cat>
482
483 · Tobias Leich <email@froggs.de>
484
485 · Wallace Reis <wallace@reis.me>
486
487 · Yury Zavarin <yury.zavarin@gmail.com>
488
489 · Oleg Kostyuk <cub@cpan.org>
490
492 This software is Copyright (c) 2018 by Stefan G. and MongoDB, Inc.
493
494 This is free software, licensed under:
495
496 The Apache License, Version 2.0, January 2004
497
498
499
500perl v5.28.1 2018-12-07 BSON(3)