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 collectionis first referenced in a command, this method is used primarily forcreating new collections that use specific options. For example, you usedb.createCollection() to create a capped collection, or to create a new collection that usesdocument validation.

db.createCollection() is a wrapper around the databasecommand create.

The db.createCollection() method has the following prototype form:

Starting in MongoDB 4.2

MongoDB removes the MMAPv1 storage engine and the MMAPv1 specificoptions paddingFactor, paddingBytes, preservePaddingfor db.createCollection().

  1. db.createCollection( <name>,
  2. {
  3. capped: <boolean>,
  4. autoIndexId: <boolean>,
  5. size: <number>,
  6. max: <number>,
  7. storageEngine: <document>,
  8. validator: <document>,
  9. validationLevel: <string>,
  10. validationAction: <string>,
  11. indexOptionDefaults: <document>,
  12. viewOn: <string>, // Added in MongoDB 3.4
  13. pipeline: <pipeline>, // Added in MongoDB 3.4
  14. collation: <document>, // Added in MongoDB 3.4
  15. writeConcern: <document>
  16. }
  17. )

The db.createCollection() method has the following parameters:

ParameterTypeDescriptionnamestringThe name of the collection to create. SeeNaming Restrictions.optionsdocumentOptional. Configuration options for creating a capped collection, forpreallocating space in a new collection, or for creating a view.

The options document contains the following fields:

FieldTypeDescriptioncappedbooleanOptional. To create a capped collection,specify true. If you specify true, you must also set a maximumsize in the size field.autoIndexIdbooleanOptional. Specify false to disable the automatic creation of an index on the_id field.

Important

Starting in MongoDB 4.0, you cannot set the option autoIndexIdto false when creating collections in databases other than thelocal database.

Deprecated since version 3.2.

sizenumberOptional. Specify a maximum size in bytes for a capped collection. Once acapped collection reaches its maximum size, MongoDB removes the olderdocuments to make space for the new documents. The size field isrequired for capped collections and ignored for other collections.maxnumberOptional. The maximum number of documents allowed in the capped collection. Thesize limit takes precedence over this limit. If a cappedcollection reaches the size limit before it reaches the maximumnumber of documents, MongoDB removes old documents. If you prefer touse the max limit, ensure that the size limit, which isrequired for a capped collection, is sufficient to contain themaximum number of documents.storageEnginedocumentOptional. Available for the WiredTiger storage engine only.

New in version 3.0.

Allows users to specify configuration to the storage engine on aper-collection basis when creating a collection. The value of thestorageEngine option should take the following form:

  1. { <storage-engine-name>: <options> }

Storage engine configuration specified when creating collections arevalidated and logged to the oplog during replication tosupport replica sets with members that use different storageengines.validatordocumentOptional. Allows users to specify validation rules or expressions for the collection. For more information,see Schema Validation.

New in version 3.2.

The validator option takes a document that specifies thevalidation rules or expressions. You can specify the expressions usingthe same operators as the query operatorswith the exception of $geoNear, $near,$nearSphere, $text, and $where.

Note

  • Validation occurs during updates and inserts. Existingdocuments do not undergo validation checks until modification.
  • You cannot specify a validator for collections in the admin,local, and config databases.
  • You cannot specify a validator for system.* collections.validationLevelstringOptional. Determines how strictly MongoDB applies thevalidation 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 allupdates."moderate"Apply validation rules to inserts and to updates on existing _valid_documents. Do not apply rules to updates on existing _invalid_documents.

validationActionstringOptional. Determines whether to error on invalid documents or just warnabout the violations but allow invalid documents to be inserted.

New in version 3.2.

Important

Validation of documents only applies to those documents asdetermined 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 failsvalidation, the write operation logs the validation failure.

indexOptionDefaultsdocumentOptional. Allows users to specify a default configuration for indexes whencreating a collection.

The indexOptionDefaults option accepts a storageEnginedocument, which should take the following form:

  1. { <storage-engine-name>: <options> }

Storage engine configuration specified when creating indexes arevalidated and logged to the oplog during replication tosupport replica sets with members that use different storageengines.

New in version 3.2.

viewOnstringThe name of the source collection or view from which to create theview. The name is not the full namespace of the collection orview; i.e. does not include the database name and implies the samedatabase as the view to create. You must create views in the samedatabase as the source collection.

See also db.createView().

New in version 3.4.

pipelinearrayAn array that consists of the aggregation pipeline stage(s). db.createView creates the view byapplying the specified pipeline to the viewOn collection or view.

The view definition pipeline cannotinclude the $out or the $merge stage. If the view definition includesnested pipeline (e.g. the view definition includes$lookup or $facet stage), thisrestriction applies to the nested pipelinesas well.

The view definition is public; i.e. db.getCollectionInfos()and explain operations on the view will include the pipeline thatdefines the view. As such, avoid referring directly to sensitive fieldsand values in view definitions.

See also db.createView().

New in version 3.4.

collationdocumentSpecifies the default collation for the collection.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

The collation option has the following syntax:

  1. collation: {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

When specifying collation, the locale field is mandatory; allother 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 unlessthe index creation operation explicitly specify a different collation.

  • Operations on that collection use the collection’s defaultcollation unless they explicitly specify a different collation.

You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.

If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons.

For a collection, you can only specify the collation during thecollection creation. Once set, you cannot modify the collection’sdefault collation.

For an example, see Specify Collation.

New in version 3.4.

writeConcerndocumentOptional. A document that expresses the write concernfor the operation. Omit to use the default writeconcern.

When issued on a sharded cluster, mongos converts thewrite concern of thecreate command and its helperdb.createCollection() to "majority".

Access Control

If the deployment enforcesauthentication/authorization,db.createCollection() requires the following privileges:

Required Privileges
Create a non-capped collectioncreateCollection on the database, orinsert on the collection to create
Create a capped collectionconvertToCapped for the collectioncreateCollection on the database
Create a view-createCollection on the databaseor-createCollection on the databaseandfind on the source collection/viewor-createCollection on the database,find on the view to create,andfind on the source collection/viewA user with createCollection on the database andfind on the view to create does not havesufficient privileges.

The readWrite built in role includes the requiredprivileges. Alternatively, you cancreate a custom role to supportdb.createCollection().

The following example uses the db.createUser() method tocreate a user in the admin database with the readWriterole on the inventory and employees database:

  1. db.getSiblingDB("admin").createUser(
  2. {
  3. "user" : "createViewUser",
  4. "pwd" : "replaceThisWithASecurePassword",
  5. "roles" : [
  6. { "db" : "inventory", "role" : "readWrite" },
  7. { "db" : "employees", "role" : "readWrite" }
  8. ]
  9. }
  10. )

The created user can execute db.createCollection() on the specified databases.For more examples of user creation, see Add Users.

Alternatively, you can add the required roles to an existing userusing db.grantRolesToUser(). For a tutorial on addingprivileges to an existing database user, seeModify Access for an Existing User.

Behavior

Resource Locking

Changed in version 4.2.

db.createCollection() obtains an exclusive lock on thespecified collection or view for the duration of the operation. Allsubsequent operations on the collection must wait untildb.createCollection() releases the lock. db.createCollection() typically holdsthis lock for a short time.

Creating a view requires obtaining an additional exclusive lockon the system.views collection in the database. This lock blockscreation or modification of views in the database until the commandcompletes.

Prior to MongoDB 4.2, db.createCollection() obtained an exclusive lockon the parent database, blocking all operations on the database _and_all its collections until the operation completed.

Examples

Create a Capped Collection

Capped collectionshave maximum size or document counts that prevent them from growingbeyond maximum thresholds. All capped collections must specify a maximumsize and may also specify a maximum document count. MongoDB removesolder documents if a collection reaches the maximum size limit before itreaches the maximum document count. Consider the following example:

  1. db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

This command creates a collection named log with a maximum size of 5megabytes and a maximum of 5000 documents.

See Capped Collections for moreinformation about capped collections.

Create a Collection with Document Validation

New in version 3.2.

Collections with validation compare each inserted or updated documentagainst the criteria specified in the validator option. Dependingon the validationLevel and validationAction, MongoDB eitherreturns a warning, or refuses to insert or update the document if itfails to meet the specified criteria.

The following example creates a contacts collection with a JSONSchema validator:

Note

MongoDB 3.6 adds the $jsonSchema operator to support JSONSchema validation.

  1. db.createCollection( "contacts", {
  2. validator: { $jsonSchema: {
  3. bsonType: "object",
  4. required: [ "phone" ],
  5. properties: {
  6. phone: {
  7. bsonType: "string",
  8. description: "must be a string and is required"
  9. },
  10. email: {
  11. bsonType : "string",
  12. pattern : "@mongodb\.com$",
  13. description: "must be a string and match the regular expression pattern"
  14. },
  15. status: {
  16. enum: [ "Unknown", "Incomplete" ],
  17. description: "can only be one of the enum values"
  18. }
  19. }
  20. } }
  21. } )

With the validator in place, the following insert operation fails validation:

  1. db.contacts.insert( { name: "Amanda", status: "Updated" } )

The method returns the error in the WriteResult:

  1. WriteResult({
  2. "nInserted" : 0,
  3. "writeError" : {
  4. "code" : 121,
  5. "errmsg" : "Document failed validation"
  6. }
  7. })

For more information, see Schema Validation. To view thevalidation specifications for a collection, use thedb.getCollectionInfos() method.

Specify Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

You can specify collation at the collection orview level. For example, the followingoperation creates a collection, specifying a collation for thecollection (See Collation Document for descriptions ofthe collation fields):

  1. db.createCollection( "myColl", { collation: { locale: "fr" } } );

This collation will be used by indexes and operations that supportcollation unless they explicitly specify a different collation. Forexample, insert the following documents into myColl:

  1. { _id: 1, category: "café" }
  2. { _id: 2, category: "cafe" }
  3. { _id: 3, category: "cafE" }

The following operation uses the collection’s collation:

  1. db.myColl.find().sort( { category: 1 } )

The operation returns documents in the following order:

  1. { "_id" : 2, "category" : "cafe" }
  2. { "_id" : 3, "category" : "cafE" }
  3. { "_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:

  1. { "_id" : 3, "category" : "cafE" }
  2. { "_id" : 2, "category" : "cafe" }
  3. { "_id" : 1, "category" : "café" }

See also

Create a View with Default Collation

Specify Storage Engine Options

New in version 3.0.

You can specify collection-specific storage engine configurationoptions when you create a collection withdb.createCollection(). Consider the following operation:

  1. db.createCollection(
  2. "users",
  3. { storageEngine: { wiredTiger: { configString: "<option>=<setting>" } } }
  4. )

This operation creates a new collection named users with aspecific configuration string that MongoDB will pass to thewiredTiger storage engine. See the WiredTiger documentation ofcollection level optionsfor specific wiredTiger options.