Navigation
This version of the documentation is archived and no longer supported. To learn how to upgrade your version of PHP Library Manual, refer to the upgrade documentation.

MongoDB\Collection::findOneAndReplace()

Definition

MongoDB\Collection::findOneAndReplace

Finds a single document matching the query and replaces it.

function findOneAndReplace($filter, $replacement, array $options = []): object|null

This method has the following parameters:

Parameter Type Description
$filter array|object The filter criteria that specifies the documents to replace.
$replacement array|object The replacement document.
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
projection array|object Optional. The projection specification to determine which fields to include in the returned documents. See Project Fields to Return from Query and Projection Operators in the MongoDB manual.
sort array|object Optional. The sort specification for the ordering of the results.
collation array|object

Optional. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

maxTimeMS integer Optional. The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
bypassDocumentValidation boolean

Optional. If true, allows the write operation to circumvent document level validation. Defaults to false.

This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation.

returnDocument integer

Optional. Specifies whether to return the document before the replacement is applied, or after. returnDocument supports the following values:

  • MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE (default)
  • MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER
session MongoDB\Driver\Session

Optional. Client session to associate with the operation.

Sessions are not supported for server versions prior to 3.6.

New in version 1.3.

typeMap array

Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection’s type map.

This will be used for the returned result document.

upsert boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.
writeConcern MongoDB\Driver\WriteConcern

Optional. Write concern to use for the operation. Defaults to the collection’s write concern.

It is not possible to specify a write concern for individual operations as part of a transaction. Instead, set the writeConcern option when starting the transaction with startTransaction.

This is not supported for server versions prior to 3.2 and will result in an exception at execution time if used.

Return Values

An array object for either the original or the replaced document, depending on the specified value of the returnDocument option. By default, the original document is returned. If no document matched the query, null is returned. The return type will depend on the typeMap option.

Errors/Exceptions

MongoDB\Exception\UnexpectedValueException if the command response from the server was malformed.

MongoDB\Exception\UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Behavior

When evaluating query criteria, MongoDB compares types and values according to its own comparison rules for BSON types, which differs from PHP’s comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class in the driver (e.g. use MongoDB\BSON\ObjectId to match an ObjectId).

Examples

Consider the following document in the restaurants collection in the test database:

{
  "_id" : ObjectId("576023c7b02fa9281da4139e"),
  "address" : {
    "building" : "977",
    "coord" : [
      -74.06940569999999,
      40.6188443
    ],
    "street" : "Bay Street",
    "zipcode" : "10305"
  },
  "borough" : "Staten Island",
  "cuisine" : "French",
  "grades" : [
    {
      "date" : ISODate("2014-08-15T00:00:00Z"),
      "grade" : "A",
      "score" : 7
    },
    {
      "date" : ISODate("2014-02-13T00:00:00Z"),
      "grade" : "A",
      "score" : 5
    },
    {
      "date" : ISODate("2013-06-07T00:00:00Z"),
      "grade" : "A",
      "score" : 11
    }
  ],
  "name" : "Zest",
  "restaurant_id" : "41220906"
}

The following operation replaces the document with restaurant_id of "41220906" with a new document:

<?php

$collection = (new MongoDB\Client)->teset->restaurants;

$replacedRestaurant = $collection->findOneAndReplace(
    [ 'restaurant_id' => '41220906' ],
    [
        'Borough' => 'Staten Island',
        'cuisine' => 'Italian',
        'grades' => [],
        'name' => 'Staten Island Pastaria',
        'restaurant_id' => '999999999',
    ],
    [ 'returnDocument' => MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER ]
);

var_dump($replacedRestaurant);

The output would then resemble:

object(MongoDB\Model\BSONDocument)#18 (1) {
  ["storage":"ArrayObject":private]=>
  array(6) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#11 (1) {
      ["oid"]=>
      string(24) "594d5ef380a846852a4b5837"
    }
    ["Borough"]=>
    string(13) "Staten Island"
    ["cuisine"]=>
    string(7) "Italian"
    ["grades"]=>
    object(MongoDB\Model\BSONArray)#17 (1) {
      ["storage":"ArrayObject":private]=>
      array(0) {
      }
    }
    ["name"]=>
    string(22) "Staten Island Pastaria"
    ["restaurant_id"]=>
    string(9) "999999999"
  }
}