1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
=============
Upgrade Guide
=============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
The |php-library| and underlying :php:`mongodb extension <mongodb>` have notable
API differences from the legacy :php:`mongo extension <mongo>`. This page will
summarize those differences for the benefit of those upgrading from the legacy
driver.
Additionally, a community-developed `mongo-php-adapter
<https://github.com/alcaeus/mongo-php-adapter>`_ library exists, which
implements the `mongo extension <http://php.net/mongo>`_ API using this library
and the new driver. While this adapter library is not officially supported by
MongoDB, it does bear mentioning.
BSON Type Classes
-----------------
When upgrading from the legacy driver,
`type classes <https://www.php.net/manual/en/mongo.types.php>`_ such as
:php:`MongoId <mongoid>` must be replaced with classes in the
`MongoDB\\BSON namespace <https://www.php.net/manual/en/book.bson.php>`_. The
new driver also introduces interfaces for its BSON types, which should be
preferred if applications need to type hint against BSON values.
The following table lists all legacy classes alongside the equivalent class in
the new driver.
.. list-table::
:header-rows: 1
* - Legacy class
- BSON type class
- BSON type interface
* - :php:`MongoId <mongoid>`
- :php:`MongoDB\\BSON\\ObjectId <mongodb_bson_objectid>`
- :php:`MongoDB\\BSON\\ObjectIdInterface <mongodb_bson_objectidinterface>`
* - :php:`MongoCode <mongocode>`
- :php:`MongoDB\\BSON\\Javascript <mongodb_bson_javascript>`
- :php:`MongoDB\\BSON\\JavascriptInterface <mongodb_bson_javascriptinterface>`
* - :php:`MongoDate <mongodate>`
- :php:`MongoDB\\BSON\\UTCDateTime <mongodb_bson_utcdatetime>`
- :php:`MongoDB\\BSON\\UTCDateTimeInterface <mongodb_bson_utcdatetimeinterface>`
* - :php:`MongoRegex <mongoregex>`
- :php:`MongoDB\\BSON\\Regex <mongodb_bson_regex>`
- :php:`MongoDB\\BSON\\RegexInterface <mongodb_bson_regexinterface>`
* - :php:`MongoBinData <mongobindata>`
- :php:`MongoDB\\BSON\\Binary <mongodb_bson_binary>`
- :php:`MongoDB\\BSON\\BinaryInterface <mongodb_bson_binaryinterface>`
* - :php:`MongoInt32 <mongoint32>`
- Not implemented. [1]_
-
* - :php:`MongoInt64 <mongoint64>`
- :php:`MongoDB\\BSON\\Int64 <mongodb_bson_int64>`
- Not implemented. [2]_
* - :php:`MongoDBRef <mongodbref>`
- Not implemented. [3]_
-
* - :php:`MongoMinKey <mongominkey>`
- :php:`MongoDB\\BSON\\MinKey <mongodb_bson_minkey>`
- :php:`MongoDB\\BSON\\MinKeyInterface <mongodb_bson_minkeyinterface>`
* - :php:`MongoMaxKey <mongomaxkey>`
- :php:`MongoDB\\BSON\\MaxKey <mongodb_bson_maxkey>`
- :php:`MongoDB\\BSON\\MaxKeyInterface <mongodb_bson_maxkeyinterface>`
* - :php:`MongoTimestamp <mongotimestamp>`
- :php:`MongoDB\\BSON\\Timestamp <mongodb_bson_timestamp>`
- :php:`MongoDB\\BSON\\TimestampInterface <mongodb_bson_timestampinterface>`
.. [1] The new driver does not implement an equivalent class for
:php:`MongoInt32 <mongoint32>`. When decoding BSON, 32-bit integers will
always be represented as a PHP integer. When encoding BSON, PHP integers will
encode as either a 32-bit or 64-bit integer depending on their value.
.. [2] :php:`MongoDB\\BSON\\Int64 <mongodb_bson_int64>` does not have an
interface defined. The new driver does not allow applications to instantiate
this type (i.e. its constructor is private) and it is only created during
BSON decoding when a 64-bit integer cannot be represented as a PHP integer on
a 32-bit platform.
.. [3] The new driver does not implement an equivalent class for
:php:`MongoDBRef <mongodbref>` since
:manual:`DBRefs </reference/database-references>` are merely a BSON document
with a particular structure and not a proper BSON type. The new driver also
does not provide any helpers for working with DBRef objects, since their use
is not encouraged.
Collection API
--------------
This library's :phpclass:`MongoDB\\Collection` class implements MongoDB's
cross-driver `CRUD
<https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_
and `Index Management
<https://github.com/mongodb/specifications/blob/master/source/index-management.rst>`_
specifications. Although some method names have changed in accordance with the
new specifications, the new class provides the same functionality as the legacy
driver's :php:`MongoCollection <mongocollection>` class with some notable
exceptions.
A guiding principle in designing the new APIs was that explicit method names are
preferable to overloaded terms found in the old API. For instance,
:php:`MongoCollection::save() <mongocollection.save>` and
:php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
have different modes of operation, depending on their arguments. Methods were
also split to distinguish between :manual:`updating specific fields
</tutorial/modify-documents>` and :manual:`full-document replacement
</tutorial/modify-documents/#replace-the-document>`.
The following table lists all legacy methods alongside the
equivalent method(s) in the new driver.
.. list-table::
:header-rows: 1
* - :php:`MongoCollection <mongocollection>` method
- :phpclass:`MongoDB\\Collection` method(s)
* - :php:`MongoCollection::aggregate() <mongocollection.aggregate>`
- :phpmethod:`MongoDB\\Collection::aggregate()`
* - :php:`MongoCollection::aggregateCursor() <mongocollection.aggregatecursor>`
- :phpmethod:`MongoDB\\Collection::aggregate()`
* - :php:`MongoCollection::batchInsert() <mongocollection.batchinsert>`
- :phpmethod:`MongoDB\\Collection::insertMany()`
* - :php:`MongoCollection::count() <mongocollection.count>`
- :phpmethod:`MongoDB\\Collection::count()`
* - :php:`MongoCollection::createDBRef() <mongocollection.createdbref>`
- Not yet implemented. [3]_
* - :php:`MongoCollection::createIndex() <mongocollection.createindex>`
- :phpmethod:`MongoDB\\Collection::createIndex()`
* - :php:`MongoCollection::deleteIndex() <mongocollection.deleteindex>`
- :phpmethod:`MongoDB\\Collection::dropIndex()`
* - :php:`MongoCollection::deleteIndexes() <mongocollection.deleteindexes>`
- :phpmethod:`MongoDB\\Collection::dropIndexes()`
* - :php:`MongoCollection::drop() <mongocollection.drop>`
- :phpmethod:`MongoDB\\Collection::drop()`
* - :php:`MongoCollection::distinct() <mongocollection.distinct>`
- :phpmethod:`MongoDB\\Collection::distinct()`
* - :php:`MongoCollection::ensureIndex() <mongocollection.ensureindex>`
- :phpmethod:`MongoDB\\Collection::createIndex()`
* - :php:`MongoCollection::find() <mongocollection.find>`
- :phpmethod:`MongoDB\\Collection::find()`
* - :php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
- :phpmethod:`MongoDB\\Collection::findOneAndDelete()`,
:phpmethod:`MongoDB\\Collection::findOneAndReplace()`, and
:phpmethod:`MongoDB\\Collection::findOneAndUpdate()`
* - :php:`MongoCollection::findOne() <mongocollection.findone>`
- :phpmethod:`MongoDB\\Collection::findOne()`
* - :php:`MongoCollection::getDBRef() <mongocollection.getdbref>`
- Not implemented. [3]_
* - :php:`MongoCollection::getIndexInfo() <mongocollection.getindexinfo>`
- :phpmethod:`MongoDB\\Collection::listIndexes()`
* - :php:`MongoCollection::getName() <mongocollection.getname>`
- :phpmethod:`MongoDB\\Collection::getCollectionName()`
* - :php:`MongoCollection::getReadPreference() <mongocollection.getreadpreference>`
- Not implemented.
* - :php:`MongoCollection::getSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::getWriteConcern() <mongocollection.getwriteconcern>`
- Not implemented.
* - :php:`MongoCollection::group() <mongocollection.group>`
- Not implemented. Use :phpmethod:`MongoDB\\Database::command()`. See
`Group Command Helper`_ for an example.
* - :php:`MongoCollection::insert() <mongocollection.insert>`
- :phpmethod:`MongoDB\\Collection::insertOne()`
* - :php:`MongoCollection::parallelCollectionScan() <mongocollection.parallelcollectionscan>`
- Not implemented.
* - :php:`MongoCollection::remove() <mongocollection.remove>`
- :phpmethod:`MongoDB\\Collection::deleteMany()` and
:phpmethod:`MongoDB\\Collection::deleteOne()`
* - :php:`MongoCollection::save() <mongocollection.save>`
- :phpmethod:`MongoDB\\Collection::insertOne()` or
:phpmethod:`MongoDB\\Collection::replaceOne()` with the ``upsert``
option.
* - :php:`MongoCollection::setReadPreference() <mongocollection.setreadpreference>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions()`.
* - :php:`MongoCollection::setSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::setWriteConcern() <mongocollection.setwriteconcern>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions()`.
* - :php:`MongoCollection::update() <mongocollection.update>`
- :phpmethod:`MongoDB\\Collection::replaceOne()`,
:phpmethod:`MongoDB\\Collection::updateMany()`, and
:phpmethod:`MongoDB\\Collection::updateOne()`.
* - :php:`MongoCollection::validate() <mongocollection.validate>`
- Not implemented.
Accessing IDs of Inserted Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the legacy driver, :php:`MongoCollection::insert() <mongocollection.insert>`,
:php:`MongoCollection::batchInsert() <mongocollection.batchinsert>`, and
:php:`MongoCollection::save() <mongocollection.save>` (when inserting) would
modify their input argument by injecting an ``_id`` key with a generated
ObjectId (i.e. :php:`MongoId <class.mongoid>` object). This behavior was a bit
of a hack, as it did not rely on the argument being :php:`passed by reference
<language.references.pass>`; instead, it directly modified memory through the
extension API and could not be implemented in PHP userland. As such, it is no
longer done in the new driver and library.
IDs of inserted documents (whether generated or not) may be accessed through the
following methods on the write result objects:
- :phpmethod:`MongoDB\\InsertOneResult::getInsertedId()` for
:phpmethod:`MongoDB\\Collection::insertOne()`
- :phpmethod:`MongoDB\\InsertManyResult::getInsertedIds()` for
:phpmethod:`MongoDB\\Collection::insertMany()`
- :phpmethod:`MongoDB\\BulkWriteResult::getInsertedIds()` for
:phpmethod:`MongoDB\\Collection::bulkWrite()`
Bulk Write Operations
~~~~~~~~~~~~~~~~~~~~~
The legacy driver's :php:`MongoWriteBatch <class.mongowritebatch>` classes have
been replaced with a general-purpose
:phpmethod:`MongoDB\\Collection::bulkWrite()` method. Whereas the legacy driver
only allowed bulk operations of the same type, the new method allows operations
to be mixed (e.g. inserts, updates, and deletes).
MongoCollection::save() Removed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:php:`MongoCollection::save() <mongocollection.save>`, which was syntactic sugar
for an insert or upsert operation, has been removed in favor of explicitly using
:phpmethod:`MongoDB\\Collection::insertOne` or
:phpmethod:`MongoDB\\Collection::replaceOne` (with the ``upsert`` option).
While the ``save`` method does have its uses for interactive environments, such
as the ``mongo`` shell, it was intentionally excluded from the
`CRUD specification <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_
for language drivers. Generally, application code should know if the document
has an identifier and be able to explicitly insert or replace the document and
handle the returned :phpclass:`MongoDB\\InsertOneResult` or
:phpclass:`MongoDB\\UpdateResult`, respectively. This also helps avoid
inadvertent and potentially dangerous :manual:`full-document replacements
</tutorial/modify-documents>`.
Group Command Helper
~~~~~~~~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does have a helper method for the
:manual:`group </reference/command/group>` command. The following example
demonstrates how to execute a group command using the
:phpmethod:`MongoDB\\Database::command()` method:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'group' => [
'ns' => 'collection_name',
'key' => ['field_name' => 1],
'initial' => ['total' => 0],
'$reduce' => new MongoDB\BSON\Javascript('...'),
],
]);
$resultDocument = $cursor->toArray()[0];