- Reference >
- MongoDB\Database Class >
- MongoDB\Database::createCollection()
MongoDB\Database::createCollection()
On this page
Definition
-
MongoDB\Database::createCollection Explicitly creates a collection.
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 mongo shell.Explicitly creating collections enables you to create capped collections, specify document validation criteria, or configure your storage engine or indexing options.
This method has the following parameters:
Parameter Type Description $collectionNamestring The name of the collection to create. $optionsarray Optional. An array specifying the desired options. The
$optionsparameter supports the following options:Option Type Description autoIndexIdboolean Optional. Specify
falseto disable the automatic creation of an index on the_idfield.Important
For replica sets, do not set
autoIndexIdtofalse.Deprecated since version 1.4: This option has been deprecated since MongoDB 3.2. As of MongoDB 4.0, this option cannot be
falsewhen creating a replicated collection (i.e. a collection outside of thelocaldatabase in any mongod mode).cappedboolean Optional. To create a capped collection, specify true. If you specifytrue, you must also set a maximum size in thesizeoption.collationarray|object Optional. Specifies the collation for the collection.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the
localefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.
expireAfterSecondsinteger Optional. Used to automatically delete documents in time series collections. See the create command documentation for more information.
This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.
New in version 1.9.
flagsinteger Optional. Available for the MMAPv1 storage engine only to set the
usePowerOf2SizesandnoPaddingflags.The MongoDB PHP Library provides constants that you can combine with a bitwise OR operator to set the flag values:
MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES:1MongoDB\Operation\CreateCollection::NO_PADDING:2
Defaults to
1.Note
MongoDB 3.0 and later ignores the
usePowerOf2Sizesflag. See collMod and db.createCollection() for more information.indexOptionDefaultsarray|object Optional. Allows users to specify a default configuration for indexes when creating a collection.
The
indexOptionDefaultsoption accepts astorageEnginedocument, 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.
maxinteger Optional. The maximum number of documents allowed in the capped collection. The sizeoption takes precedence over this limit. If a capped collection reaches thesizelimit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use themaxlimit, ensure that thesizelimit, which is required for a capped collection, is sufficient to contain the maximum number of documents.maxTimeMSinteger Optional. The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point. sessionMongoDB\Driver\Session Optional. Client session to associate with the operation.
Sessions are not supported for server versions prior to 3.6.
New in version 1.3.
sizeinteger Optional. Specify 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. The sizeoption is required for capped collections and ignored for other collections.storageEnginearray|object Optional. Available 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
storageEngineoption 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|object Optional. An object containing options for creating time series collections. See the create command documentation for supported options.
This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.
New in version 1.9.
typeMaparray Optional. The 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.
validatorarray|object Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation in the MongoDB manual.
The
validatoroption 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$geoNear,$near,$nearSphere,$text, and$where.Note
- 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, andconfigdatabases. - You cannot specify a validator for
system.*collections.
validationActionstring Optional. Determines whether to
erroron invalid documents or justwarnabout the violations but allow invalid documents to be inserted.Important
Validation of documents only applies to those documents as determined by the
validationLevel.validationActionDescription "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. validationLevelstring Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.
validationLevelDescription "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. writeConcernMongoDB\Driver\WriteConcern Optional. Write concern to use for the operation. Defaults to the database’s write concern.
This is not supported for server versions prior to 3.4 and will result in an exception at execution time if used.
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 create command reference in the MongoDB manual for compatibility considerations.
Return Values
An array or object with the result document of the create command.
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 driver level (e.g. connection errors).
Example
The following example creates a users collection in the test
database with document validation criteria:
The output would then resemble:
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
See Also
- create command reference in the MongoDB manual
- db.createCollection()
- Time Series Collections