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::insertOne()

Definition

MongoDB\Collection::insertOne

Insert one document.

function insertOne($document, array $options = []): MongoDB\InsertOneResult

This method has the following parameters:

Parameter Type Description
$document array|object The document to insert into the collection.
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
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.

writeConcern MongoDB\Driver\WriteConcern Optional. Write concern to use for the operation. Defaults to the collection’s write concern.

Return Values

A MongoDB\InsertOneResult object, which encapsulates a MongoDB\Driver\WriteResult object.

Errors/Exceptions

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

MongoDB\Driver\Exception\BulkWriteException for errors related to the write operation. Users should inspect the value returned by getWriteResult() to determine the nature of the error.

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

Behavior

If a MongoDB\Driver\Exception\BulkWriteException is thrown, users should call getWriteResult() and inspect the returned MongoDB\Driver\WriteResult object to determine the nature of the error.

For example, a write operation may have been successfully applied to the primary server but failed to satisfy the write concern (e.g. replication took too long). Alternatively, a write operation may have failed outright (e.g. unique key violation).

Example

The following operation inserts a document into the users collection in the test database:

<?php

$collection = (new MongoDB\Client)->test->users;

$insertOneResult = $collection->insertOne([
    'username' => 'admin',
    'email' => 'admin@example.com',
    'name' => 'Admin User',
]);

printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());

var_dump($insertOneResult->getInsertedId());

The output would then resemble:

Inserted 1 document(s)
object(MongoDB\BSON\ObjectID)#11 (1) {
  ["oid"]=>
  string(24) "579a25921f417dd1e5518141"
}