1MongoDB::Upgrading::v1(U3s)er Contributed Perl DocumentatMioonngoDB::Upgrading::v1(3)
2
3
4
6 MongoDB::Upgrading::v1 - Deprecations and behavior changes from v0 to
7 v1
8
10 version v2.2.2
11
13 The v1 driver represents a substantial step forward in functionality
14 and consistency. There are many areas where the old API has been
15 deprecated or changed in a backward breaking way.
16
17 This document is intended to help developers update their code to take
18 into account API changes from the v0 driver to the v1 driver.
19
21 Changes to the driver were deemed necessary to achieve certain goals:
22
23 · consistency (intra-driver) – many parts of the v0 API were
24 inconsistent, behaving differently from method to method; the v1
25 API minimizes developer surprises by improving consistency in
26 return types and exception mechanisms.
27
28 · consistency (inter-driver) — "next-generation" MongoDB drivers
29 across all languages are converging on common APIs and common
30 behaviors; this simplifies developer education and support, as
31 cross-language examples will be similar.
32
33 · encapsulation – too many low-level, internal operations were
34 exposed as part of the API, which complicates maintenance work; the
35 v1 API aims to minimize the "public surface" available to
36 developers, allowing faster future development keeping up with
37 MongoDB server enhancements with less risk of breakage.
38
39 · abstraction – many v0 methods returned raw server documents for
40 end-user code to inspect, which is brittle in the face of changes
41 in server responses over time; the v1 API uses result classes to
42 abstract the details behind standardized accessors.
43
44 · server compatibility – some new features and behavior changes in
45 the MongoDB server no longer fit the old driver design; the v1
46 driver transparently supports both old and new servers.
47
48 · portability – the v0 driver had a large dependency tree and
49 substantial non-portable C code; the v1 driver removes some
50 dependencies and uses widely-used, well-tested CPAN modules in
51 place of custom C code where possible; it lays the groundwork for a
52 future "pure-Perl optional" driver.
53
54 · round-trippable data – the v0 BSON implementation could easily
55 change data types when round-tripping documents; the v1 driver is
56 designed to round-trip data correctly whenever possible (within the
57 limits of Perl's dynamic typing).
58
60 Moo instead of Moose
61 The v1 driver uses Moo instead of Moose. This change results in a
62 slightly faster driver and a significantly reduced deep dependency
63 tree.
64
65 SSL and SASL
66 The v0 driver required a compiler and OpenSSL and libgsasl for SSL and
67 SASL support, respectively. The v1 driver instead relies on CPAN
68 modules "IO::Socket::SSL" and "Authen::SASL" for SSL and SASL support,
69 respectively.
70
71 SSL configuration is now possible via the ssl attribute.
72
73 Authentication configuration is described in "AUTHENTICATION" in
74 MongoDB::MongoClient.
75
77 MongoClient configuration
78 New configuration options
79
80 Several configuration options have been added, with particular emphasis
81 on adding more granular control of timings and timeout behaviors.
82
83 · "auth_mechanism"
84
85 · "auth_mechanism_properties"
86
87 · "bson_codec"
88
89 · "connect_timeout_ms"
90
91 · "heartbeat_frequency_ms"
92
93 · "local_threshold_ms"
94
95 · "max_time_ms"
96
97 · "replica_set_name"
98
99 · "read_pref_mode"
100
101 · "read_pref_tag_sets"
102
103 · "server_selection_timeout_ms"
104
105 · "socket_check_interval_ms"
106
107 · "socket_timeout_ms"
108
109 Replica set configuration
110
111 Connecting to a replica set now requires a replica set name, given
112 either with the "replica_set_name" option for MongoDB::MongoClient or
113 with the "replicaSet" option in a connection string. For example:
114
115 $client = MongoDB::MongoClient->new(
116 host => "mongodb://rs1.example.com,rs2.example.com/",
117 replica_set_name => 'the_set',
118 );
119
120 $client = MongoDB::MongoClient->new(
121 host => "mongodb://rs1.example.com,rs2.example.com/?replicaSet=the_set"
122 );
123
124 Configuration options changed to read-only
125
126 Configuration options are changing to be immutable to prevent
127 surprising action-at-a-distance. (E.g. changing an attribute value in
128 some part of the code changes it for other parts of the code that
129 didn't expect it.) Going forward, options may be set at
130 MongoDB::MongoClient construction time only.
131
132 The following options have changed to be read-only:
133
134 · "db_name"
135
136 · "j"
137
138 · "password"
139
140 · "ssl"
141
142 · "username"
143
144 · "w"
145
146 · "wtimeout"
147
148 Write concern may be overridden at the MongoDB::Database and
149 MongoDB::Collection level during construction of those objects. For
150 more details, see the later section on write concern changes.
151
152 Mapping between connection string and configuration options
153
154 Many configuration options may be set via a connection string URI in
155 the "host" option. In the v0 driver, the precedence between the
156 connection string and constructor options was completely inconsistent.
157 In the v1 driver, options set via a connection string URI will take
158 precedence over options passed to the constructor. This is consistent
159 with with other MongoDB drivers (as well as how DBI treats Data Source
160 Names).
161
162 The list of servers and ports as well as the optional "username",
163 "password" and "db_name" options come directly from URI structure.
164 Other options are parsed as key-value parameters at the end of the
165 connection string. The following table shows how connection string
166 keys map to configuration options in the MongoDB::MongoClient:
167
168 Connection String Key MongoClient option
169 --------------------------- -----------------------------
170 authMechanism auth_mechanism
171 authMechanismProperties auth_mechanism_properties
172 connectTimeoutMS connect_timeout_ms
173 heartbeatFrequencyMS heartbeat_frequency_ms
174 journal j
175 localThresholdMS local_threshold_ms
176 maxTimeMS max_time_ms
177 readPreference read_pref_mode
178 readPreferenceTags read_pref_tag_sets
179 replicaSet replica_set_name
180 serverSelectionTimeoutMS server_selection_timeout_ms
181 socketCheckIntervalMS socket_check_interval_ms
182 socketTimeoutMS socket_timeout_ms
183 ssl ssl
184 w w
185 wTimeoutMS wtimeout
186
187 The "readPreferenceTags" and "authMechanismProperties" keys take colon-
188 delimited, comma-separated pairs:
189
190 readPreferenceTags=dc:nyeast,rack:1
191 authMechanismProperties=SERVICE_NAME:mongodb
192
193 The "readPreferenceTags" option may be repeated to build up a list of
194 tag set documents:
195
196 readPreferenceTags=dc:nyc,rack:1&readPreferenceTags=dc:nyc
197
198 Deprecated configuration options
199
200 Several options have been superseded, replaced or renamed for clarity
201 and are thus deprecated and undocumented. They are kept for a limited
202 degree of backwards compatibility. They will be generally be used as
203 fallbacks for other options. If any were read-write, they have also
204 been changed to read-only.
205
206 · "dt_type" — see "BSON encoding changes" for details.
207
208 · "query_timeout" — replaced by "socket_timeout_ms"; if set, this
209 will be used as a fallback default for "socket_timeout_ms".
210
211 · "sasl" — superseded by "auth_mechanism"; if set, this will be used
212 along with "sasl_mechanism" as a fallback default for
213 "auth_mechanism".
214
215 · "sasl_mechanism" — superseded by "auth_mechanism"; if set, this
216 will be used as a fallback default for "auth_mechanism".
217
218 · "timeout" — replaced by "connect_timeout_ms"; if set, this will be
219 used as a fallback default for "connect_timeout_ms".
220
221 These will be removed in a future major release.
222
223 Configuration options removed
224
225 Some configuration options have been removed entirely, as they no
226 longer serve any purpose given changes to server discovery, server
227 selection and connection handling:
228
229 · "auto_connect"
230
231 · "auto_reconnect"
232
233 · "find_master"
234
235 · "max_bson_size"
236
237 As described further below in the "BSON encoding changes" section,
238 these BSON encoding configuration options have been removed as well:
239
240 · "inflate_dbrefs"
241
242 · "inflate_regexps"
243
244 Removed configuration options will be ignored if passed to the
245 MongoDB::MongoClient constructor.
246
247 Lazy connections and reconnections on demand
248 The improved approach to server monitoring and selection allows all
249 connections to be lazy. When the client is constructed, no connections
250 are made until the first network operation is needed. At that time,
251 the client will scan all servers in the seed list and begin regular
252 monitoring. Connections that drop will be re-established when needed.
253
254 IMPORTANT: Code that used to rely on a fatal exception from
255 "MongoDB::MongoClient->new" when no mongod is available will break.
256 Instead, users are advised to just conduct their operations and be
257 prepared to handle errors.
258
259 For testing, users may wish to run a simple command to check that a
260 mongod is ready:
261
262 use Test::More;
263
264 # OLD WAY: BROKEN
265 plan skip_all => 'no mongod' unless eval {
266 MongoDB::MongoClient->new
267 };
268
269 # NEW WAY 1: with MongoDB::MongoClient
270 plan skip_all => 'no mongod' unless eval {
271 MongoDB::MongoClient->new->db('admin')->run_command(
272 [ ismaster => 1 ]
273 )
274 };
275
276 # NEW WAY 2: with MongoDB and connect
277 plan skip_all => 'no mongod' unless eval {
278 MongoDB->connect->db('admin')->run_command([ ismaster => 1 ])
279 };
280
281 See SERVER SELECTION and SERVER MONITORING AND FAILOVER in
282 MongoDB::MongoClient for details.
283
284 Exceptions are the preferred error handling approach
285 In the v0 driver, errors could be indicated in various ways:
286
287 · boolean return value
288
289 · string return value is an error; hash ref is success
290
291 · document that might contain an 'err', 'errmsg' or '$err' field
292
293 · thrown string exception
294
295 Regardless of the documented error handling, every method that involved
296 a network operation would throw an exception on various network errors.
297
298 In the v1 driver, exceptions objects are the standard way of indicating
299 errors. The exception hierarchy is described in MongoDB::Error.
300
301 Cursors and query responses
302 In v0, MongoDB::Cursor objects were used for ordinary queries as well
303 as the query-like commands aggregation and parallel scan. However,
304 only cursor iteration commands worked for aggregation and parallel scan
305 "cursors"; the rest of the MongoDB::Cursor API didn't apply and was
306 fatal.
307
308 In v1, all result iteration is done via the new MongoDB::QueryResult
309 class. MongoDB::Cursor is now just a thin wrapper that holds query
310 parameters, instantiates a MongoDB::QueryResult on demand, and passes
311 iteration methods through to the query result object.
312
313 This significantly simplifies the code base and should have little end-
314 user visibility unless users are specifically checking the return type
315 of queries and query-like methods.
316
317 The "explain" cursor method no longer resets the cursor.
318
319 The "slave_okay" cursor method now sets the "read_preference" to
320 'secondaryPreferred' or clears it to 'primary'.
321
322 The "snapshot" cursor method now requires a boolean argument, allowing
323 it to be turned on or off before executing the query. Calling it
324 without an argument (as it was in v0) is a fatal exception.
325
326 Parallel scan "cursors" are now QueryResult objects, with the same
327 iteration methods as in v0.
328
329 The $MongoDB::Cursor::slave_okay global variable has been removed as
330 part of the revision to read preference handling. See the read
331 preferences section below for more details.
332
333 The $MongoDB::Cursor::timeout global variable has also been removed.
334 Timeouts are set during MongoDB::MongoClient configuration and are
335 immutable. See the section on configuration changes for more.
336
337 Aggregation API
338 On MongoDB 2.6 or later, "aggregate" always uses a cursor to execute
339 the query. The "batchSize" option has been added (but has no effect
340 prior to 2.6). The "cursor" option is deprecated.
341
342 The return types for the "aggregate" method are now always QueryResult
343 objects, regardless of whether the aggregation uses a cursor internally
344 or is an 'explain'.
345
346 NOTE: To help users with a 2.6 mongos and mixed version shards with
347 versions before 2.6, passing the deprecated 'cursor' option with a
348 false value will disable the use of a cursor. This workaround is
349 provided for convenience and will be removed when 2.4 is no longer
350 supported.
351
352 Read preference objects and the read_preference method
353 A new MongoDB::ReadPreference class is used to encapsulate read
354 preference attributes. In the v1 driver, it is constructed from the
355 "read_pref_mode" and "read_pref_tag_sets" attributes on
356 MongoDB::MongoClient:
357
358 MongoDB::MongoClient->new(
359 read_pref_mode => 'primaryPreferred',
360 read_pref_tag_sets => [ { dc => 'useast' }, {} ],
361 );
362
363 The old "read_preference" method to change the read preference has been
364 removed and trying to set a read preference after the client has been
365 created is a fatal error. The old mode constants PRIMARY, SECONDARY,
366 etc. have been removed.
367
368 The "read_preference" method now returns the MongoDB::ReadPreference
369 object generated from "read_pref_mode" and "read_pref_tag_sets".
370
371 It is inherited by MongoDB::Database, MongoDB::Collection, and
372 MongoDB::GridFS objects unless provided as an option to the relevant
373 factory methods:
374
375 my $coll = $db->get_collection(
376 "foo", { read_preference => 'secondary' }
377 );
378
379 Such "read_preference" arguments may be a MongoDB::ReadPreference
380 object, a hash reference of arguments to construct one, or a string
381 that represents the read preference mode.
382
383 MongoDB::Database and MongoDB::Collection also have "clone" methods
384 that allow easy alteration of a read preference for a limited scope.
385
386 my $coll2 = $coll->clone( read_preference => 'secondaryPreferred' );
387
388 For MongoDB::Cursor, the "read_preference" method sets a hidden read
389 preference attribute that is used for the query in place of the
390 MongoDB::MongoClient default "read_preference" attribute. This means
391 that calling "read_preference" on a cursor object no longer changes the
392 read preference globally on the client – the read preference change is
393 scoped to the cursor object only.
394
395 Write concern objects and removing the safe argument
396 A new MongoDB::WriteConcern class is used to encapsulate write concern
397 attributes. In the v1 driver, it is constructed from the "w",
398 "wtimeout" and "j" attributes on MongoDB::MongoClient:
399
400 MongoDB::MongoClient->new( w => 'majority', wtimeout => 1000 );
401
402 The "write_concern" method now returns the MongoDB::WriteConcern object
403 generated from "w", "wtimeout" and "j".
404
405 It is inherited by MongoDB::Database, MongoDB::Collection, and
406 MongoDB::GridFS objects unless provided as an option to the relevant
407 factory methods:
408
409 $db = $client->get_database(
410 "test", { write_concern => { w => 'majority' } }
411 );
412
413 Such "write_concern" arguments may be a MongoDB::WriteConcern object, a
414 hash reference of arguments to construct one, or a string that
415 represents the "w" mode.
416
417 MongoDB::Database and MongoDB::Collection also have "clone" methods
418 that allow easy alteration of a write concern for a limited scope.
419
420 my $coll2 = $coll->clone( write_concern => { w => 1 } );
421
422 The "safe" argument is no longer used in the new CRUD API.
423
424 Authentication based only on configuration options
425 Authentication now happens automatically on connection during the
426 "handshake" with any given server based on the auth_mechanism
427 attribute.
428
429 The old "authenticate" method in MongoDB::MongoClient has been removed.
430
431 Bulk API
432 Bulk method names changed to match CRUD API
433
434 Method names match the new CRUD API, e.g. "insert_one" instead of
435 "insert" and so one. The legacy names are deprecated.
436
437 Bulk insertion
438
439 Insertion via the bulk API will NOT insert an "_id" into the original
440 document if one does not exist. Previous documentation was not
441 specific whether this was the case or if the "_id" was added to the
442 document sent to the server.
443
444 Bulk write results
445
446 The bulk write results class has been renamed to
447 MongoDB::BulkWriteResult. It keeps "MongoDB::WriteResult" as an empty
448 superclass for some backwards compatibility so that
449 "$result->isa("MongoDB::WriteResult")" will continue to work as
450 expected.
451
452 The attributes have been renamed to be consistent with the new CRUD
453 API. The legacy names are deprecated, but are available as aliases.
454
455 GridFS
456 The MongoDB::GridFS class now has explicit read preference and write
457 concern attributes inherited from MongoDB::MongoClient or
458 MongoDB::Database, just like MongoDB::Collection. This means that
459 GridFS operations now default to an acknowledged write concern, just
460 like collection operations have been doing since v0.502.0 in 2012.
461
462 The use of "safe" is deprecated.
463
464 Support for ancient, undocumented positional parameters circa 2010 has
465 been removed.
466
467 Low-level functions removed
468 Low-level driver functions have been removed from the public API.
469
470 MongoDB::Connection removed
471 The "MongoDB::Connection" module was deprecated in v0.502.0 and has
472 been removed.
473
474 BSON encoding changes
475 In the v1 driver, BSON encoding and decoding have been encapsulated
476 into a MongoDB::BSON codec object. This can be provided at any level,
477 from MongoDB::MongoClient to MongoDB::Collection. If not provided, a
478 default will be created that behaves similarly to the v0
479 encoding/decoding functions, except for the following changes.
480
481 $MongoDB::BSON::use_binary removed
482
483 Historically, this defaulted to false, which corrupts binary data when
484 round tripping. Retrieving a binary data element and re-inserting it
485 would have resulted in a field with UTF-8 encoded string of binary
486 data.
487
488 Going forward, binary data will be returned as a MongoDB::BSON::Binary
489 object. A future driver may add the ability to control decoding to
490 allow alternative representations.
491
492 $MongoDB::BSON::use_boolean removed
493
494 This global variable never worked. BSON booleans were always
495 deserialized as boolean objects. A future driver may add the ability
496 to control boolean representation.
497
498 $MongoDB::BSON::utf8_flag_on removed
499
500 In order to ensure round-tripping of string data, this variable is
501 removed. BSON strings will always be decoded to Perl character
502 strings. Anything else risks double-encoding a round-trip.
503
504 $MongoDB::BSON::looks_like_number and $MongoDB::BSON::char deprecated
505 and re-scoped
506
507 In order to allow a future driver to provide more flexible user-
508 customized encoding and decoding, these global variables are
509 deprecated. If set, they will be examined during
510 "MongoDB::MongoClient->new()" to set the configuration of a default
511 MongoDB::BSON codec (if one is not provided). Changing them later will
512 NOT change the behavior of the codec object.
513
514 "MongoDB::MongoClient" option "inflate_regexps" removed
515
516 Previously, BSON regular expressions decoded to "qr{}" references by
517 default and the "MongoDB::MongoClient" "inflate_regexps" option was
518 available to decode instead to MongoDB::BSON::Regexps.
519
520 Going forward in the v1.0.0 driver, for safety and consistency with
521 other drivers, BSON regular expressions always decode to
522 MongoDB::BSON::Regexp objects.
523
524 "MongoDB::MongoClient" option "inflate_dbrefs" removed
525
526 The "inflate_dbrefs" configuration option has been removed and replaced
527 with a "dbref_callback" option in MongoDB::BSON.
528
529 By default, the "MongoDB::MongoClient" will create a MongoDB::BSON
530 codec that will construct MongoDB::DBRef objects. This ensures that
531 DBRefs properly round-trip.
532
533 "MongoDB::MongoClient" option "dt_type" deprecated and changed to read-
534 only
535
536 The "dt_type" option is now only takes effect if "MongoDB::MongoClient"
537 constructs a MongoDB::BSON codec object. It has been changed to a
538 read-only attribute so that any code that relied on changing "dt_type"
539 after constructing a "MongoDB::MongoClient" object will fail instead of
540 being silently ignored.
541
542 Int32 vs Int64 encoding changes
543
544 On 64-bit Perls, integers that fit in 32-bits will be encoded as BSON
545 Int32 (whereas previously these were always encoded as BSON Int64).
546
547 Math::BigInt objects will always be encoded as BSON Int64, which allows
548 users to force 64-bit encoding if desired.
549
550 Added support for Time::Moment
551
552 Time::Moment is a much faster replacement for the venerable DateTime
553 module. The BSON codec will serialize Time::Moment objects correctly
554 and can use that module as an argument for the "dt_type" codec
555 attribute.
556
557 Added support for encoding common JSON boolean classes
558
559 Most JSON libraries on CPAN implement their own boolean classes. The
560 following libraries boolean types will now encode correctly as BSON
561 booleans:
562
563 · JSON::XS
564
565 · Cpanel::JSON::XS
566
567 · JSON::PP
568
569 · JSON::Tiny
570
571 · Mojo::JSON
572
573 DBRef objects
574 The "fetch" method and related attributes "client", "verify_db", and
575 "verify_coll" have been removed from MongoDB::DBRef.
576
577 Providing a "fetch" method was inconsistent with other MongoDB drivers,
578 which either never provided it, or have dropped it in the next-
579 generation drivers. It requires a "client" attribute, which tightly
580 couples BSON decoding to the client model, causing circular reference
581 issues and triggering Perl memory bugs under threads. Therefore, the
582 v1.0.0 driver no longer support fetching directly from MongoDB::DBRef;
583 users will need to implement their own methods for dereferencing.
584
585 Additionally, the "db" attribute is now optional, consistent with the
586 specification for DBRefs.
587
588 Also, all attributes ("ref", "id" and "db") are now read-only,
589 consistent with the move toward immutable objects throughout the
590 driver.
591
592 To support round-tripping DBRefs with additional fields other than
593 $ref, $id and $db, the DBRef class now has an attribute called "extra".
594 As not all drivers support this feature, using it for new DBRefs is not
595 recommended.
596
598 Deprecated options and methods may be removed in a future release.
599 Their documentation has been removed to discourage ongoing use. Unless
600 otherwise stated, they will continue to behave as they previously did,
601 allowing a degree of backwards compatibility until code is updated to
602 the new MongoDB driver API.
603
604 MongoDB::Database
605 · eval – MongoDB 3.0 deprecated the '$eval' command, so this helper
606 method is deprecated as well.
607
608 · last_error — Errors are now indicated via exceptions at the time
609 database commands are executed.
610
611 MongoDB::Collection
612 · insert, batch_insert, remove, update, save, query and
613 find_and_modify — A new common driver CRUD API replaces these
614 legacy methods.
615
616 · get_collection — This method implied that collections could be
617 contained inside collection. This doesn't actually happen so it's
618 confusing to have a Collection be a factory for collections. Users
619 who want nested namespaces should be explicit and create them off
620 Database objects instead.
621
622 · ensure_index, drop_indexes, drop_index, get_index — A new
623 MongoDB::IndexView class is accessible through the "indexes"
624 method, offering greater consistency in behavior across drivers.
625
626 · validate — The return values have changed over different server
627 versions, so this method is risky to use; it has more use as a one-
628 off tool, which can be accomplished via "run_command".
629
630 MongoDB::CommandResult
631 · result — has been renamed to 'output' for clarity
632
633 MongoDB::Cursor
634 · slave_ok — this modifier method is superseded by the
635 'read_preference' modifier method
636
637 · count — this is superseded by the "MongoDB::Collection#count" in
638 MongoDB::Collection count method. Previously, this ignored
639 skip/limit unless a true argument was passed, which was a bizarre,
640 non-intuitive and inconsistent API.
641
642 MongoDB::BulkWrite and MongoDB::BulkWriteView
643 · insert — renamed to 'insert_one' for consistency with CRUD API
644
645 · update — renamed to 'update_many' for consistency with CRUD API
646
647 · remove — renamed to 'delete_many' for consistency with CRUD API
648
649 · remove_one — renamed to 'delete_one' for consistency with CRUD API
650
652 · David Golden <david@mongodb.com>
653
654 · Rassi <rassi@mongodb.com>
655
656 · Mike Friedman <friedo@friedo.com>
657
658 · Kristina Chodorow <k.chodorow@gmail.com>
659
660 · Florian Ragwitz <rafl@debian.org>
661
663 This software is Copyright (c) 2020 by MongoDB, Inc.
664
665 This is free software, licensed under:
666
667 The Apache License, Version 2.0, January 2004
668
669
670
671perl v5.32.0 2020-08-18 MongoDB::Upgrading::v1(3)