Navigation
This version of the documentation is archived and no longer supported.

create

Definition

create

Changed in version 3.4: Added support for the creation of views and the specification of Collation.

Explicitly creates a collection or view. create has the following form:

{
  create: <collection or view name>,
  capped: <true|false>,
  autoIndexId: <true|false>,
  size: <max_size>,
  max: <max_documents>,
  flags: <0|1|2|3>,
  storageEngine: <document>,
  validator: <document>,
  validationLevel: <string>,
  validationAction: <string>,
  indexOptionDefaults: <document>,
  viewOn: <source>,
  pipeline: <pipeline>,
  collation: <document>
}

create has the following fields:

Field Type Description
create string The name of the new collection or view. See Naming Restrictions.
capped boolean Optional. To create a capped collection, specify true. If you specify true, you must also set a maximum size in the size field.
autoIndexId boolean

Optional. Specify false to disable the automatic creation of an index on the _id field.

Important

For replica sets, do not set autoIndexId to false.

Deprecated since version 3.2.

size 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 size field is required for capped collections and ignored for other collections.
max integer Optional. The maximum number of documents allowed in the capped collection. The size limit takes precedence over this limit. If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use the max limit, ensure that the size limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.
flags integer

Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flags. To set, specify one of the following values:

Note

MongoDB 3.0 ignores the usePowerOf2Sizes flag. See collMod and db.createCollection() for more information.

Defaults to 1.

New in version 2.6.

Changed in version 3.0.0: Add support for setting the new noPadding flag.

Warning

Do not set noPadding if the workload includes removes or any updates that may cause documents to grow. For more information, see No Padding Allocation Strategy.

storageEngine document

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 storageEngine option 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.

validator document

Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation.

New in version 3.2.

The validator option 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, and config databases.
  • You cannot specify a validator for system.* collections.
validationLevel string

Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.

New in version 3.2.

validationLevel Description
"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.
validationAction string

Optional. Determines whether to error on invalid documents or just warn about 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.

validationAction Description
"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.
indexOptionDefaults document

Optional. Allows users to specify a default configuration for indexes when creating a collection.

The indexOptionDefaults option accepts a storageEngine document, 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.

viewOn 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 db.createView().

New in version 3.4.

pipeline array

An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view.

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.

See also db.createView().

New in version 3.4.

collation  

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:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field 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 explictly specify a different collation.

  • Operations on that collection use the collection’s default collation unless they explictly 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 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.

The db.createCollection() method and the db.createView() method wrap the create command.

Considerations

The create command obtains a write lock on the affected database and will block other operations until it has completed. The write lock for this operation is typically short lived. However, allocations for large capped collections may take longer.

Access Control

If the deployment enforces authentication/authorization, create requires the following privileges:

  Required Privileges
Create a non-capped collection

createCollection on the database, or

insert on the collection to create

Create a capped collection

convertToCapped for the collection

createCollection on the database

Create a view

A user with createCollection on the database and find on the view to create does not have sufficient privileges.

The readWrite built in role includes the required privileges. Alternatively, you can create a custom role to support create.

The following example uses the db.createUser() method to create a user in the admin database with the readWrite role on the inventory and employees database:

db.getSiblingDB("admin").createUser(
  {
    "user" : "createViewUser",
    "pwd" : "replaceThisWithASecurePassword",
    "roles" : [
      { "db" : "inventory", "role" : "readWrite" },
      { "db" : "employees", "role" : "readWrite" }
    ]
  }
)

The created user can execute create on the specified databases. For more examples of user creation, see Add Users.

Alternatively, you can add the required roles to an existing user using db.grantRolesToUser(). For a tutorial on adding privileges to an existing database user, see Modify Access for 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 View

New in version 3.4.

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, given a collection survey with the following documents:

{ _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.

See also

db.createView()

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

New in version 3.0.

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.

←   copydb createIndexes  →