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

.. 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::insertMany()

   Insert multiple documents.

20
   .. code-block:: php
21

22 23
      function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult

24
   This method has the following parameters:
25

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

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

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

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

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

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

.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

44 45 46 47 48
Example
-------

.. start-crud-include

49 50
The following operation inserts two documents into the ``users`` collection
in the ``example`` database:
51 52

.. code-block:: php
53

54 55
   <?php

56
   $collection = (new MongoDB\Client)->example->users;
57

58
   $insertManyResult = $collection->insertMany([
59 60 61
       [
           'username' => 'admin',
           'email' => 'admin@example.com',
62 63 64
           'name' => 'Admin User',
       ],
       [
65 66
           'username' => 'test',
           'email' => 'test@example.com',
67 68 69
           'name' => 'Test User',
       ],
   ]);
70

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

73 74 75
   var_dump($insertManyResult->getInsertedIds());

The output would then resemble::
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

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

91
.. end-crud-include
92

93 94 95 96 97 98 99 100
See Also
--------

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