@@ -23,8 +23,11 @@ implements the ``mongo`` extension API using this library and the new driver.
23
23
While this adapter library is not officially supported by MongoDB, it does bear
24
24
mentioning.
25
25
26
- BSON Type Classes
27
- -----------------
26
+ BSON
27
+ ----
28
+
29
+ Type Classes
30
+ ~~~~~~~~~~~~
28
31
29
32
When upgrading from the legacy driver, type classes such as MongoId must be
30
33
replaced with classes in the
@@ -103,6 +106,70 @@ the new driver.
103
106
driver also does not provide any helpers for working with DBRef objects,
104
107
since their use is not encouraged.
105
108
109
+ Emulating the Legacy Driver
110
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
111
+
112
+ The legacy ``mongo`` extension returned both BSON documents and arrays as PHP
113
+ arrays. While PHP arrays are convenient to work with, this behavior was
114
+ problematic:
115
+
116
+ - Different BSON types could deserialize to the same PHP value (e.g.
117
+ ``{"0": "foo"}`` and ``["foo"]``), which made it impossible to infer the
118
+ original BSON type.
119
+
120
+ - Numerically-indexed PHP arrays would be serialized as BSON documents if there
121
+ was a gap in their key sequence. Such gaps were easily caused by unsetting a
122
+ key to remove an element and forgetting to numerically reindex the array.
123
+
124
+ The |php-library|'s :phpclass:`BSONDocument <MongoDB\\Model\\BSONDocument>` and
125
+ :phpclass:`BSONArray <MongoDB\\Model\\BSONArray>` classes address these concerns
126
+ by preserving the BSON type information during serialization and
127
+ deserialization; however, some users may still prefer the legacy behavior. If
128
+ desired, you can use the ``typeMap`` option to have the library return
129
+ everything as a PHP array:
130
+
131
+ .. code-block:: php
132
+
133
+ <?php
134
+
135
+ $client = new MongoDB\Client(
136
+ 'mongodb://127.0.0.1/',
137
+ [],
138
+ [
139
+ 'typeMap' => [
140
+ 'array' => 'array',
141
+ 'document' => 'array',
142
+ 'root' => 'array',
143
+ ],
144
+ ]
145
+ );
146
+
147
+ $document = $client->test->zips->findOne(['_id' => '94301']);
148
+
149
+ var_dump($document);
150
+
151
+ The above example would output something similar to:
152
+
153
+ .. code-block:: php
154
+
155
+ array(5) {
156
+ ["_id"]=>
157
+ string(5) "94301"
158
+ ["city"]=>
159
+ string(9) "PALO ALTO"
160
+ ["loc"]=>
161
+ array(2) {
162
+ [0]=>
163
+ float(-122.149685)
164
+ [1]=>
165
+ float(37.444324)
166
+ }
167
+ ["pop"]=>
168
+ int(15965)
169
+ ["state"]=>
170
+ string(2) "CA"
171
+ }
172
+
106
173
Collection API
107
174
--------------
108
175
0 commit comments