- Reference >
mongoshMethods >- Database Methods >
- db.createCollection()
db.createCollection()¶
On this page
Definition¶
-
db.createCollection(name, options)¶ Creates a new collection or view. For views, see also
db.createView().Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this method is used primarily for creating new collections that use specific options. For example, you use
db.createCollection()to create a:- Capped collection.
- Clustered collection.
- New collection that uses document validation.
db.createCollection()is a wrapper around the database commandcreate.The
db.createCollection()method has the following prototype form:Note
Starting in MongoDB 4.2
MongoDB removes the MMAPv1 storage engine and the MMAPv1 specific options
paddingFactor,paddingBytes,preservePaddingfordb.createCollection().The
db.createCollection()method has the following parameters:Parameter Type Description namestring The name of the collection to create. See Naming Restrictions. optionsdocument Optional. Configuration options for creating a:
- Capped collection
- Custered collection
- View
The
optionsdocument contains the following fields:Field Type Description cappedboolean Optional. To create a capped collection, specify true. If you specifytrue, you must also set a maximum size in thesizefield.timeseries.timeFieldstring Required when creating a time series collection. The name of the field which contains the date in each time series document. Documents in a time series collection must have a valid BSON date as the value for the timeField.timeseries.metaFieldstring Optional. The name of the field which contains metadata in each time series document. The metadata in the specified field should be data that is used to label a unique series of documents. The metadata should rarely, if ever, change.
The name of the specified field may not be
_idor the same as thetimeseries.timeField. The field can be of any type except array.timeseries.granularitystring Optional. Possible values are "seconds"(default),"minutes", and"hours". Set the granularity to the value that is the closest match to the time span between consecutive incoming measurements. Setting thegranularityparameter improves performance by optimizing how data in the time series collection is stored internally.expireAfterSeconds number Optional. Specifies the seconds after which documents in a time series collection or clustered collection expire. MongoDB deletes expired documents automatically.
For clustered collections, the documents are deleted automatically based on the clustered index key
_idand the values must be date types. See TTL Indexes.clusteredIndex document Starting in MongoDB 5.3, you can create a collection with a clustered index. Collections created with a clustered index are called clustered collections.
clusteredIndexhas the following syntax:Field Description keyRequired. The clustered index key field. Must be set to { _id: 1 }. The default value for the_idfield is an automatically generated unique object identifier, but you can set your own clustered index key values.uniqueRequired. Must be set to true. A unique index indicates the collection will not accept inserted or updated documents where the clustered index key value matches an existing value in the index.nameOptional. A name that uniquely identifies the clustered index. New in version 5.3.
changeStreamPreAndPostImages document Optional.
Starting in MongoDB 6.0, you can use change stream events to output the version of a document before and after changes (the document pre- and post-images):
- The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.
- The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.
- Enable
changeStreamPreAndPostImagesfor a collection usingdb.createCollection(),create, orcollMod.
changeStreamPreAndPostImageshas the following syntax:enabledDescription trueEnables change stream pre- and post-images for a collection. falseDisables change stream pre- and post-images for a collection. For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.
For a
db.createCollection()example on this page, see Create a Collection with Change Stream Pre- and Post-Images for Documents.New in version 6.0.
autoIndexIdboolean Optional. Specify
falseto disable the automatic creation of an index on the_idfield.Important
Starting in MongoDB 4.0, you cannot set the option
autoIndexIdtofalsewhen creating collections in databases other than thelocaldatabase.Deprecated since version 3.2.
sizenumber 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 sizefield is required for capped collections and ignored for other collections.maxnumber Optional. The maximum number of documents allowed in the capped collection. The sizelimit 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.storageEnginedocument 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 configuration specified when creating collections are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.
See also
validatordocument Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Schema Validation.
The
validatoroption takes a document that specifies the validation rules or expressions. You can specify the expressions using the same operators as the query operators with the exception of$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.
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. 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. indexOptionDefaultsdocument 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 configuration specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.
viewOnstring The 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. does not include the database name and implies the same database as the view to create. You must create views in the same database as the source collection.
See also
db.createView().pipelinearray An array that consists of the aggregation pipeline stage(s).
db.createViewcreates the view by applying the specifiedpipelineto theviewOncollection or view.A view definition
pipelinecannot include the$outor the$mergestage. This restriction also applies to embedded pipelines, such as pipelines used in$lookupor$facetstages.The view definition is public; i.e.
db.getCollectionInfos()andexplainoperations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.See also
db.createView().collationdocument Specifies the default collation for the collection.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
The collation option has the following syntax:
When specifying collation, the
localefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.If you specify a collation at the collection level:
Indexes on that collection will be created with that collation unless the index creation operation explicitly specify a different collation.
Operations on that collection use the collection’s default collation unless they explicitly specify a different collation.
You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.
If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.
For a collection, you can only specify the collation during the collection creation. Once set, you cannot modify the collection’s default collation.
For an example, see Specify Collation.
writeConcerndocument Optional. A document that expresses the write concern for the operation. Omit to use the default write concern.
When issued on a sharded cluster,
mongosconverts the write concern of thecreatecommand and its helperdb.createCollection()to"majority".
Access Control¶
If the deployment enforces
authentication/authorization,
db.createCollection() requires the following privileges:
| Task | Required Privileges |
|---|---|
| Create a non-capped collection |
|
| Create a capped collection |
|
| Create a view |
However, if the user has the |
A user with the readWrite built in role on the database
has the required privileges to run the listed operations. Either
create a user with the required role
or grant the role to an existing user.
Behavior¶
Resource Locking¶
Changed in version 4.2.
db.createCollection() obtains an exclusive lock on the
specified collection or view for the duration of the operation. All
subsequent operations on the collection must wait until
db.createCollection() releases the lock. db.createCollection() typically holds
this lock for a short time.
Creating a view requires obtaining an additional exclusive lock
on the system.views collection in the database. This lock blocks
creation or modification of views in the database until the command
completes.
Transactions¶
Changed in version 4.4.
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is :red:`not` a cross-shard write transaction.
To use db.createCollection() in a transaction, the transaction must use read
concern "local". If you specify a read concern level
other than "local", the transaction fails.
Examples¶
Create a Capped Collection¶
Capped collections have maximum size or document counts that prevent them from growing beyond maximum thresholds. All capped collections must specify a maximum size and may also specify a maximum document count. MongoDB removes older documents if a collection reaches the maximum size limit before it reaches the maximum document count. Consider the following example:
This command creates a collection named log with a maximum size of 5
megabytes and a maximum of 5000 documents.
See Capped Collections for more information about capped collections.
Create a Time Series Collection¶
To create a time series collection that captures weather data for the past 24 hours, issue this command:
Create a Clustered Collection¶
The following db.createCollection() example adds a
clustered collection named stocks:
In the example, clusteredIndex specifies:
"key": { _id: 1 }, which sets the clustered index key to the_idfield."unique": true, which indicates the clustered index key value must be unique."name": "stocks clustered key", which sets the clustered index name.
Create a Collection with Change Stream Pre- and Post-Images for Documents¶
Starting in MongoDB 6.0, you can use change stream events to output the version of a document before and after changes (the document pre- and post-images):
- The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.
- The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.
- Enable
changeStreamPreAndPostImagesfor a collection usingdb.createCollection(),create, orcollMod.
The following example creates a collection that has changeStreamPreAndPostImages enabled:
Pre- and post-images are not available for a change stream event if the images were:
Not enabled on the collection at the time of a document update or delete operation.
Removed after the pre- and post-image retention time set in
expireAfterSeconds.The following example sets
expireAfterSecondsto100seconds:The following example returns the current
changeStreamOptionssettings, includingexpireAfterSeconds:Setting
expireAfterSecondstooffuses the default retention policy: pre- and post-images are retained until the corresponding change stream events are removed from the oplog.If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the
expireAfterSecondspre- and post-image retention time.
Additional considerations:
- Enabling pre- and post-images consumes storage space and adds processing time. Only enable pre- and post-images if you need them.
- Limit the change stream event size to less than 16 megabytes. To limit
the event size, you can:
- Limit the document size to 8 megabytes. You can request pre- and
post-images simultaneously in the change stream output if other change stream event fields like
updateDescriptionare not large. - Request only post-images in the change stream output for documents
up to 16 megabytes if other change stream event fields like
updateDescriptionare not large. - Request only pre-images in the change stream output for documents up
to 16 megabytes if:
- document updates affect only a small fraction of the document structure or content, and
- do not cause a
replacechange event. Areplaceevent always includes the post-image.
- Limit the document size to 8 megabytes. You can request pre- and
post-images simultaneously in the change stream output if other change stream event fields like
- To request a pre-image, you set
fullDocumentBeforeChangetorequiredorwhenAvailableindb.collection.watch(). To request a post-image, you setfullDocumentusing the same method. - Pre-images are written to the
config.system.preimagescollection.- The
config.system.preimagescollection may become large. To limit the collection size, you can setexpireAfterSecondstime for the pre-images as shown earlier. - Pre-images are removed asynchronously by a background process.
- The
Important
Backward-Incompatible Feature
Starting in MongoDB 6.0, if you are using document pre- and post-images
for change streams, you must disable
changeStreamPreAndPostImages for each collection using
the collMod command before you can downgrade to an earlier
MongoDB version.
See also
- For change stream events and output, see Change Events.
- To watch a collection for changes, see
db.collection.watch. - For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.
Create a Collection with Document Validation¶
Collections with validation compare each inserted or updated document
against the criteria specified in the validator option. Depending
on the validationLevel and validationAction, MongoDB either
returns a warning, or refuses to insert or update the document if it
fails to meet the specified criteria.
The following example creates a contacts collection with a JSON
Schema validator:
With the validator in place, the following insert operation fails validation:
The method returns the error:
To view the validation specifications for a collection, use
db.getCollectionInfos().
See also
Specify Collation¶
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
You can specify collation at the collection or view level. For example, the following operation creates a collection, specifying a collation for the collection (See Collation Document for descriptions of the collation fields):
This collation will be used by indexes and operations that support
collation unless they explicitly specify a different collation. For
example, insert the following documents into myColl:
The following operation uses the collection’s collation:
The operation returns documents in the following order:
The same operation on a collection that uses simple binary collation (i.e. no specific collation set) returns documents in the following order:
See also
Specify Storage Engine Options¶
You can specify collection-specific storage engine configuration
options when you create a collection with
db.createCollection(). Consider the following operation:
This operation creates a new collection named users with a
specific configuration string that MongoDB will pass to the
wiredTiger storage engine. See the :wtdocs-v5.0:`WiredTiger documentation of
collection level options </struct_w_t___s_e_s_s_i_o_n.html>`
for specific wiredTiger options.