create
Definition
create
Explicitly creates a collection or view.
Note
The view created by this command does not refer to materialized views. For discussion of on-demand materialized views, see
$merge
instead.
Compatibility
This command 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 create
command has the following syntax:
Note
MongoDB 6.3 adds the bucketMaxSpanSeconds
and
bucketRoundingSeconds
parameters. To downgrade below 6.3, you
must either drop all collections with these parameters, or modify
them to use the corresponding granularity
, if possible. For
details see collMod
.
{ create: <collection or view name>, capped: <true|false>, timeseries: { timeField: <string>, metaField: <string>, granularity: <string> }, expireAfterSeconds: <number>, autoIndexId: <true|false>, size: <max_size>, max: <max_documents>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <source>, pipeline: <pipeline>, collation: <document>, writeConcern: <document>, comment: <any> }
Command Fields
The create
command has the following fields:
Field | Type | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| string | The name of the new collection or view. See Naming Restrictions. | ||||||||||
| 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. Possible values are | ||||||||||
| number | Optional. Enable the automatic deletion of documents in a time series collection by specifying the number of seconds after which documents expire. MongoDB deletes expired documents automatically. | ||||||||||
| boolean | Optional. Specify ImportantStarting in MongoDB 4.0, you cannot set the option Deprecated since version 3.2. | ||||||||||
| integer | 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 | ||||||||||
| integer | 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 more information, see Specify Storage Engine Options. | ||||||||||
| document | Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Schema Validation. New in version 3.2. The
| ||||||||||
| string | Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update. New in version 3.2.
| ||||||||||
| string | Optional. Determines whether to 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. New in version 3.2. | ||||||||||
| string | 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 New in version 3.4. | ||||||||||
| array | An array that consists of the aggregation pipeline stage(s). The view definition The view definition is public; i.e. See also | ||||||||||
| Specifies the default collation for the collection or the view. 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 view, if no collation is specified, the view's default collation is the "simple" binary comparison collator. For a view on a collection, the view does not inherit the collection's collation settings. For a view on another view, the to be created view must specify the same collation settings. After you create the collection or the view, you cannot update its default collation. For an example that specifies the default collation during the creation of a collection, see Specify Collation. New in version 3.4. | |||||||||||
| 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, | ||||||||||
| any | Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:
A comment can be any valid BSON type (string, integer, object, array, etc). New in version 4.4. |
The db.createCollection()
method and the
db.createView()
method wrap the create
command.
Behavior
Resource Locking
Changed in version 4.2.
create
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
create
releases the lock. create
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, create
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 create
in a transaction, the transaction must use read
concern "local"
. If you specify a read concern level
other than "local"
, the transaction fails.
Stable API
Changed in version 5.0.
When using Stable API V1, you cannot specify
the following fields in a create
command:
autoIndexId
capped
indexOptionDefaults
max
size
storageEngine
Access Control
If the deployment enforces
authentication/authorization,
create
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.
Examples
Create a Capped Collection
To create a capped collection limited to 64 kilobytes, issue the command in the following form:
db.runCommand( { create: "collection", capped: true, size: 64 * 1024 } )
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 } )
Note
In this example expireAfterSeconds
is specified as 86400
which means documents expire 86400
seconds after the
timestamp
value. See Set up Automatic Removal for Time Series Collections (TTL).
Create a View
Note
The view created by this command does not refer to materialized
views. For discussion of on-demand materialized views, see
$merge
instead.
Changed in version 4.2.
The view definition pipeline
cannot
include the $out
or the $merge
stage. If the view definition includes
nested pipeline (e.g. the view definition includes
$lookup
or $facet
stage), this
restriction applies to the nested pipelines
as well.
To create a view using the create
command, use the following syntax:
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline> } )
or if specifying a collation:
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )
For example, create a survey
collection with the following documents:
db.survey.insertMany( [ { _id: 1, empNumber: "abc123", feedback: { management: 3, environment: 3 }, department: "A" }, { _id: 2, empNumber: "xyz987", feedback: { management: 2, environment: 3 }, department: "B" }, { _id: 3, empNumber: "ijk555", feedback: { management: 3, environment: 4 }, department: "A" } ] )
The following operation creates a managementRatings
view with the
_id
, feedback.management
, and department
fields:
db.runCommand ( { create: "managementFeedback", viewOn: "survey", pipeline: [ { $project: { "management": "$feedback.management", department: 1 } } ] } )
Important
The view definition is public; i.e. db.getCollectionInfos()
and explain
operations on the view will include the pipeline that
defines the view. As such, avoid referring directly to sensitive fields
and values in view definitions.
Specify Collation
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.runCommand ( { create: "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.runCommand( { create: "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. See the WiredTiger documentation of
collection level options
for specific wiredTiger
options.