MongoDB\Database::createCollection()
Definition
MongoDB\Database::createCollection()
Explicitly creates a collection.
function createCollection( string $collectionName, array $options = [] ): void 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
MongoDB\Database::createCollection()
method, or using db.createCollection() in the MongoDB shell.Explicitly creating collections enables you to create capped collections, specify document validation criteria, or configure your storage engine or indexing options.
Parameters
$collectionName
: string- The name of the collection to create.
$options
: arrayAn array specifying the desired options.
Note
Not all options are available on all versions of MongoDB. Refer to the create command reference in the MongoDB manual for compatibility considerations.
NameTypeDescriptioncappedbooleanTo create a capped collection, specifytrue
. If you specifytrue
, you must also set a maximum size in thesize
option.changeStreamPreAndPostImagesdocumentUsed to configure support for pre- and post-images in change streams. See the create command documentation for more information.
This option is available since MongoDB 6.0 and will result in an exception at execution time if specified for an older server version.
New in version 1.13.
clusteredIndexdocumentA clustered index specification. See Clustered Collections or the create command documentation for more information.
This option is available since MongoDB 5.3 and will result in an exception at execution time if specified for an older server version.
New in version 1.13.
collationarray|objectCollation 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.commentmixedEnables users to specify an arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.
This option is available since MongoDB 4.4 and will result in an exception at execution time if specified for an older server version.
New in version 1.13.
encryptedFieldsdocumentA document describing encrypted fields for queryable encryption. If omitted, the
encryptedFieldsMap
option within theautoEncryption
driver option will be consulted. See Field Encryption and Queryability in the MongoDB manual for more information.This option is available since MongoDB 7.0 and will result in an exception at execution time if specified for an older server version.
New in version 1.13.
expireAfterSecondsintegerUsed to automatically delete documents in time series collections. See the create command documentation for more information.
This option is available since MongoDB 5.0 and will result in an exception at execution time if specified for an older server version.
New in version 1.9.
indexOptionDefaultsarray|objectAllows users to specify a default configuration for indexes when creating a collection.
The
indexOptionDefaults
option accepts astorageEngine
document, which should take the following form:{ <storage-engine-name>: <options> } Storage engine configurations specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.
maxintegerThe maximum number of documents allowed in the capped collection. Thesize
option takes precedence over this limit. If a capped collection reaches thesize
limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use themax
limit, ensure that thesize
limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.maxTimeMSintegerThe cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
pipelinearrayAn array that consists of the aggregation pipeline stage(s), which will be applied to the collection or view specified by
viewOn
. See the create command documentation for more information.New in version 1.13.
sessionClient session to associate with the operation.
New in version 1.3.
sizeintegerSpecify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents. Thesize
option is required for capped collections and ignored for other collections.storageEnginearray|objectAvailable for the WiredTiger storage engine only.
Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection. The value of the
storageEngine
option should take the following form:{ <storage-engine-name>: <options> } Storage engine configurations specified when creating collections are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.
timeseriesarray|objectAn object containing options for creating time series collections. See the create command documentation for supported options.
This option is available since MongoDB 5.0 and will result in an exception at execution time if specified for an older server version.
New in version 1.9.
typeMaparrayThe type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the database's type map.
This will be used for the returned command result document.
validationActionstringDetermines whether to
error
on invalid documents or justwarn
about the violations but allow invalid documents to be inserted.Important
Validation of documents only applies to those documents as determined by the
validationLevel
.validationAction
Description"error"
Default. Documents must pass validation before the write occurs. Otherwise, the write operation fails."warn"
Documents do not have to pass validation. If the document fails validation, the write operation logs the validation failure.validationLevelstringDetermines how strictly MongoDB applies the validation rules to existing documents during an update.
validationLevel
Description"off"
No validation for inserts or updates."strict"
Default. Apply validation rules to all inserts and all updates."moderate"
Apply validation rules to inserts and to updates on existing valid documents. Do not apply rules to updates on existing invalid documents.validatorarray|objectAllows users to specify validation rules or expressions for the collection. For more information, see Document Validation in the MongoDB manual.
The
validator
option takes an array that specifies the validation rules or expressions. You can specify the expressions using the same operators as MongoDB's query operators with the exception of$near
,$nearSphere
,$text
, and$where
.Validation occurs during updates and inserts. Existing documents do not undergo validation checks until modification.
You cannot specify a validator for collections in the
admin
,local
, andconfig
databases.You cannot specify a validator for
system.*
collections.viewOnstringThe name of the source collection or view from which to create the view.
The name is not the full namespace of the collection or view (i.e. it does not include the database name). Views must be created in the same databases as the source collection or view.
New in version 1.13.
writeConcernWrite concern to use for the operation. Defaults to the database's write concern.
Errors/Exceptions
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 extension level (e.g. connection errors).
Example
The following example creates a users
collection in the test
database with document validation criteria:
$db = (new MongoDB\Client)->test; $db->createCollection('users', [ 'validator' => [ 'username' => ['$type' => 'string'], 'email' => ['$regex' => '@mongodb\.com$'], ], ]);
See Also
create command reference in the MongoDB manual