Navigation

Legacy Driver Upgrade Guide

Overview

The MongoDB PHP Library and underlying mongodb extension have notable API differences from the legacy mongo extension. This page will summarize those differences for the benefit of those upgrading from the legacy driver.

Additionally, a community-developed mongo-php-adapter library exists, which implements the mongo extension 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 such as MongoId must be replaced with classes in the MongoDB\BSON namespace. 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.

Legacy class BSON type class BSON type interface
MongoId MongoDB\BSON\ObjectId MongoDB\BSON\ObjectIdInterface
MongoCode MongoDB\BSON\Javascript MongoDB\BSON\JavascriptInterface
MongoDate MongoDB\BSON\UTCDateTime MongoDB\BSON\UTCDateTimeInterface
MongoRegex MongoDB\BSON\Regex MongoDB\BSON\RegexInterface
MongoBinData MongoDB\BSON\Binary MongoDB\BSON\BinaryInterface
MongoInt32 Not implemented. [1]  
MongoInt64 MongoDB\BSON\Int64 Not implemented. [2]
MongoDBRef Not implemented. [3]  
MongoMinKey MongoDB\BSON\MinKey MongoDB\BSON\MinKeyInterface
MongoMaxKey MongoDB\BSON\MaxKey MongoDB\BSON\MaxKeyInterface
MongoTimestamp MongoDB\BSON\Timestamp MongoDB\BSON\TimestampInterface
[1]The new driver does not implement an equivalent class for 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]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](1, 2, 3) The new driver does not implement an equivalent class for MongoDBRef since DBRefs 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.

Emulating the Legacy Driver

The legacy mongo extension returned both BSON documents and arrays as PHP arrays. While PHP arrays are convenient to work with, this behavior was problematic:

  • Different BSON types could deserialize to the same PHP value (e.g. {"0": "foo"} and ["foo"]), which made it impossible to infer the original BSON type.
  • Numerically-indexed PHP arrays would be serialized as BSON documents if there was a gap in their key sequence. Such gaps were caused by unsetting a key to remove an element and forgetting to numerically reindex the array.

The MongoDB PHP Library’s BSONDocument and BSONArray classes address these concerns by preserving the BSON type information during serialization and deserialization; however, some users may still prefer the legacy behavior. If desired, you can use the typeMap option to have the library return everything as a PHP array:

<?php

$client = new MongoDB\Client(
    'mongodb://127.0.0.1/',
    [],
    [
        'typeMap' => [
            'array' => 'array',
            'document' => 'array',
            'root' => 'array',
        ],
    ]
);

$document = $client->test->zips->findOne(['_id' => '94301']);

var_dump($document);

The above example would output something similar to:

array(5) {
  ["_id"]=>
  string(5) "94301"
  ["city"]=>
  string(9) "PALO ALTO"
  ["loc"]=>
  array(2) {
    [0]=>
    float(-122.149685)
    [1]=>
    float(37.444324)
  }
  ["pop"]=>
  int(15965)
  ["state"]=>
  string(2) "CA"
}

Collection API

This library’s MongoDB\Collection class implements MongoDB’s cross-driver CRUD and Index Management 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 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, MongoCollection::save() and MongoCollection::findAndModify() have different modes of operation, depending on their arguments. Methods were also split to distinguish between updating specific fields and full-document replacement.

The following table lists all legacy methods alongside the equivalent method(s) in the new driver.

MongoCollection method MongoDB\Collection method(s)
MongoCollection::aggregate() MongoDB\Collection::aggregate()
MongoCollection::aggregateCursor() MongoDB\Collection::aggregate()
MongoCollection::batchInsert() MongoDB\Collection::insertMany()
MongoCollection::count() MongoDB\Collection::count()
MongoCollection::createDBRef() Not yet implemented. [3]
MongoCollection::createIndex() MongoDB\Collection::createIndex()
MongoCollection::deleteIndex() MongoDB\Collection::dropIndex()
MongoCollection::deleteIndexes() MongoDB\Collection::dropIndexes()
MongoCollection::drop() MongoDB\Collection::drop()
MongoCollection::distinct() MongoDB\Collection::distinct()
MongoCollection::ensureIndex() MongoDB\Collection::createIndex()
MongoCollection::find() MongoDB\Collection::find()
MongoCollection::findAndModify() MongoDB\Collection::findOneAndDelete(), MongoDB\Collection::findOneAndReplace(), and MongoDB\Collection::findOneAndUpdate()
MongoCollection::findOne() MongoDB\Collection::findOne()
MongoCollection::getDBRef() Not implemented. [3]
MongoCollection::getIndexInfo() MongoDB\Collection::listIndexes()
MongoCollection::getName() MongoDB\Collection::getCollectionName()
MongoCollection::getReadPreference() MongoDB\Collection::getReadPreference()
MongoCollection::getSlaveOkay() Not implemented.
MongoCollection::getWriteConcern() MongoDB\Collection::getWriteConcern()
MongoCollection::group() Not implemented. Use MongoDB\Database::command(). See Group Command Helper for an example.
MongoCollection::insert() MongoDB\Collection::insertOne()
MongoCollection::parallelCollectionScan() Not implemented.
MongoCollection::remove() MongoDB\Collection::deleteMany() and MongoDB\Collection::deleteOne()
MongoCollection::save() MongoDB\Collection::insertOne() or MongoDB\Collection::replaceOne() with the upsert option.
MongoCollection::setReadPreference() Not implemented. Use MongoDB\Collection::withOptions().
MongoCollection::setSlaveOkay() Not implemented.
MongoCollection::setWriteConcern() Not implemented. Use MongoDB\Collection::withOptions().
MongoCollection::update() MongoDB\Collection::replaceOne(), MongoDB\Collection::updateMany(), and MongoDB\Collection::updateOne().
MongoCollection::validate() Not implemented.

Accessing IDs of Inserted Documents

In the legacy driver, MongoCollection::insert(), MongoCollection::batchInsert(), and MongoCollection::save() (when inserting) would modify their input argument by injecting an _id key with a generated ObjectId (i.e. MongoId object). This behavior was a bit of a hack, as it did not rely on the argument being passed by reference; 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:

Bulk Write Operations

The legacy driver’s MongoWriteBatch classes have been replaced with a general-purpose 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

MongoCollection::save(), which was syntactic sugar for an insert or upsert operation, has been removed in favor of explicitly using MongoDB\Collection::insertOne() or MongoDB\Collection::replaceOne() (with the upsert option).

While the save method does have its uses for interactive environments, such as the MongoDB shell, it was intentionally excluded from the CRUD specification 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 MongoDB\InsertOneResult or MongoDB\UpdateResult, respectively. This also helps avoid inadvertent and potentially dangerous full-document replacements.

Group Command Helper

MongoDB\Collection does not have a helper method for the group command. The following example demonstrates how to execute a group command using the MongoDB\Database::command() method:

<?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];