On this page
db.createCollection()
On this page
Definition
db.createCollection( name, options )-
Changed in version 3.4: Added support for:
- Creation of views (see also
db.createView()). - Collation.
Creates a new collection or view.
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.The
db.createCollection()method has the following prototype form:db.createCollection(<name>, { capped: <boolean>, autoIndexId: <boolean>, size: <number>, max: <number>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <string>, pipeline: <pipeline>, collation: <document> } )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, for preallocating space in a new collection, or for creating a 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.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 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.usePowerOf2Sizesboolean Optional. Available for the MMAPv1 storage engine only.
Deprecated since version 3.0: For the MMAPv1 storage engine, all collections use the power of 2 sizes allocation unless the
noPaddingoption istrue. TheusePowerOf2Sizesoption does not affect the allocation strategy.noPaddingboolean Optional. Available for the MMAPv1 storage engine only.
New in version 3.0:
noPaddingflag disables the power of 2 sizes allocation for the collection. WithnoPaddingflag set to true, the allocation strategy does not include additional space to accommodate document growth, as such, document growth will result in new allocation. Use for collections with workloads that are insert-only or in-place updates (such as incrementing counters).Defaults to
false.Warning
Do not set
noPaddingif the workload includes removes or any updates that may cause documents to grow. For more information, see No Padding Allocation Strategy.storageEnginedocument Optional. Available for the WiredTiger storage engine only.
New in version 3.0.
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 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.
validatordocument Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Schema Validation.
New in version 3.2.
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$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.
validationLevelstring Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.
New in version 3.2.
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.New in version 3.2.
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-name>: <options> }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.
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().New in version 3.4.
pipelinearray An array that consists of the aggregation pipeline stage.
db.createViewcreates the view by applying the specifiedpipelineto theviewOncollection or view.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().New in version 3.4.
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:
collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> }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.
New in version 3.4.
- Creation of views (see also
Access Control
If the deployment enforces authentication/authorization, db.createCollection() requires the following privileges:
| Required Privileges | |
|---|---|
| Create a non-capped collection |
|
| Create a capped collection |