db.createCollection()
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, or to create a new collection that uses document validation.db.createCollection()
is a wrapper around the database commandcreate
.
Compatibility
This method is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The db.createCollection()
method has the following
prototype form:
db.createCollection( <name>, { capped: <boolean>, timeseries: { // Added in MongoDB 5.0 timeField: <string>, // required for time series collections metaField: <string>, granularity: <string> }, expireAfterSeconds: <number>, clusteredIndex: <document>, // Added in MongoDB 5.3 changeStreamPreAndPostImages: <document>, // Added in MongoDB 6.0 size: <number>, max: <number>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <string>, pipeline: <pipeline>, collation: <document>, writeConcern: <document> } )
The db.createCollection()
method has the following parameters:
Parameter | Type | Description |
---|---|---|
| string | The name of the collection to create. See Naming Restrictions. |
| document | Optional. Configuration options for creating a:
|
The options
document contains the following fields:
Field | Type | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| boolean | Optional. To create a capped collection,
specify | ||||||||||
| string | 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 | ||||||||||
| string | 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 | ||||||||||
| string | Optional, do not use if setting Set For more information on granularity and bucket intervals, see Set Granularity for Time Series Data. | ||||||||||
| number | Optional. Specifies the seconds after which documents in a time series collection expire. MongoDB deletes expired documents automatically. | ||||||||||
| number | 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 | ||||||||||
| number | Optional. The maximum number of documents allowed in the capped
collection. The | ||||||||||
| document | 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
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. For details, see Specify Storage Engine Options. | ||||||||||
| document | Optional. Allows users to specify validation rules or expressions for the collection. The To learn how to create a collection with schema validation, see JSON Schema. | ||||||||||
| string | Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.
| ||||||||||
| string | Optional. Determines whether to IMPORTANT: Validation of documents only applies to those
documents as determined by the | ||||||||||
| document | Optional. Allows users to specify a default configuration for indexes when creating a collection. The
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. | ||||||||||
| string | The name of the source collection or view from which to create
a view. For details, see | ||||||||||
| array | An array that consists of the aggregation pipeline stage(s). | ||||||||||
| document | 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 If you specify a collation at the collection level:
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. | ||||||||||
| document | Optional. A document that expresses the write concern for the operation. Omit to use the default write concern. When issued on a sharded cluster, |
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.
Prior to MongoDB 4.2, db.createCollection()
obtained an exclusive lock
on the parent database, blocking all operations on the database and
all its collections until the operation completed.
Transactions
Changed in version 4.4.
You can create collections and indexes inside a distributed transaction if the transaction is 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:
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
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:
db.createCollection( "weather24h", { timeseries: { timeField: "timestamp", metaField: "data", granularity: "hours" }, expireAfterSeconds: 86400 } )
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:
db.createCollection( "contacts", { validator: { $jsonSchema: { bsonType: "object", required: [ "phone" ], properties: { phone: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType : "string", pattern : "@mongodb\.com$", description: "must be a string and match the regular expression pattern" }, status: { enum: [ "Unknown", "Incomplete" ], description: "can only be one of the enum values" } } } } } )
With the validator in place, the following insert operation fails validation:
db.contacts.insertOne( { name: "Amanda", status: "Updated" } )
The method returns the error:
Uncaught: MongoServerError: Document failed validation Additional information: { failingDocumentId: ObjectId("61a8f4847a818411619e952e"), details: { operatorName: '$jsonSchema', schemaRulesNotSatisfied: [ { operatorName: 'properties', propertiesNotSatisfied: [ { propertyName: 'status', description: 'can only be one of the enum values', details: [ [Object] ] } ] }, { operatorName: 'required', specifiedAs: { required: [ 'phone' ] }, missingProperties: [ 'phone' ] } ] } }
To view the validation specifications for a collection, use
db.getCollectionInfos()
.
Specify Collation
New in version 3.4.
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):
db.createCollection( "myColl", { collation: { locale: "fr" } } );
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
:
{ _id: 1, category: "café" } { _id: 2, category: "cafe" } { _id: 3, category: "cafE" }
The following operation uses the collection's collation:
db.myColl.find().sort( { category: 1 } )
The operation returns documents in the following order:
{ "_id" : 2, "category" : "cafe" } { "_id" : 3, "category" : "cafE" } { "_id" : 1, "category" : "café" }
The same operation on a collection that uses simple binary collation (i.e. no specific collation set) returns documents in the following order:
{ "_id" : 3, "category" : "cafE" } { "_id" : 2, "category" : "cafe" } { "_id" : 1, "category" : "café" }
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:
db.createCollection( "users", { storageEngine: { wiredTiger: { configString: "<option>=<setting>" } } } )
This operation creates a new collection named users
with a
specific configuration string that MongoDB will pass to the
wiredTiger
storage engine.
For example, to specify the zlib
compressor for file blocks in the
users
collection, set the block_compressor
option with the
following command:
db.createCollection( "users", { storageEngine: { wiredTiger: { configString: "block_compressor=zlib" } } } )