MongoDBCollection-insertOne.txt 2.07 KB
Newer Older
1 2 3 4 5
================================
MongoDB\\Collection::insertOne()
================================

.. default-domain:: mongodb
6

7 8 9 10 11 12 13 14 15
.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

16 17 18 19
.. phpmethod:: MongoDB\\Collection::insertOne()

   Insert one document.

20
   .. code-block:: php
21

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

24
   This method has the following parameters:
25

26 27 28
   .. include:: /includes/apiargs/MongoDBCollection-method-insertOne-param.rst

   The ``$options`` parameter supports the following options:
29

30 31
   .. include:: /includes/apiargs/MongoDBCollection-method-insertOne-option.rst

32 33
Return Values
-------------
34

35 36
A :phpclass:`MongoDB\\InsertOneResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult <class.mongodb-driver-writeresult>` object.
37

38 39 40 41
Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-invalidargumentexception.rst
42
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
43 44
.. include:: /includes/extracts/error-driver-runtimeexception.rst

45 46 47 48 49
Behavior
--------

.. include:: /includes/extracts/bulkwriteexception-result.rst

50 51 52
Example
-------

53 54 55
.. start-crud-include

The following operation inserts a document into the ``users`` collection in the
56
``test`` database:
57 58

.. code-block:: php
59

60 61
   <?php

62
   $collection = (new MongoDB\Client)->test->users;
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

   $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"
   }

.. end-crud-include
83

84 85 86 87 88 89 90 91
See Also
--------

- :phpmethod:`MongoDB\\Collection::insertMany()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`insert </reference/command/insert>` command reference in the MongoDB
  manual