1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
=====================================
MongoDB\\Database::createCollection()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::createCollection
Explicitly creates a collection.
.. code-block:: php
function createCollection($collectionName, array $options = []): array|object
MongoDB creates collections implicitly when you first reference
the collection in a command, such as when inserting a document
into a new collection. You may also explicitly create a collection
with specific options using the ``createCollection()``
method, or using :dbcommand:`create` in the :program:`mongo` shell.
Explicitly creating collections enables you to create
:manual:`capped collections </core/capped-collections>`, specify
:manual:`document validation criteria </core/document-validation>`,
or configure your storage engine or indexing options.
:phpmethod:`MongoDB\\Database::createCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-option.rst
Note that not all options are available on all versions of MongoDB.
Document Validation, for example, was added in MongoDB 3.2;
similarly, the WiredTiger storage engine is available only for
MongoDB 3.0 and later. Refer to the :manual:`create command
</reference/command/create>` reference in the MongoDB manual for
compatibility considerations.
Output
------
Returns the command result document as an array.
Example
-------
The following example creates a ``users`` collection in the ``demo``
database with document validation criteria:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$result = $db->createCollection('users', [
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result);
The output would then resemble::
Object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
.. seealso::
:manual:`create </reference/command/create>` command reference in
the MongoDB manual