翻译或纠错本页面

db.createCollection()

On this page

Definition

db.createCollection(name, options)

在 3.4 版更改: Added support for:

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 also used to pre-allocate space for an ordinary collection.

db.createCollection() is a wrapper around the database command create.

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
name string The name of the collection to create.
options document Optional. Configuration options for creating a capped collection, for preallocating space in a new collection, or for creating a view.

The options document contains the following fields:

Field Type Description
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.

重要

For replica sets, do not set autoIndexId to false.

3.2 版后已移除: The autoIndexId option will be removed in version 3.4.

size 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 size field is required for capped collections and ignored for other collections.
max number 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.
usePowerOf2Sizes boolean

Optional. Available for the MMAPv1 storage engine only.

3.0 版后已移除: For the MMAPv1 storage engine, all collections use the power of 2 sizes allocation unless the noPadding option is true. The usePowerOf2Sizes option does not affect the allocation strategy.

noPadding boolean

Optional. Available for the MMAPv1 storage engine only.

3.0 新版功能: noPadding flag disables the power of 2 sizes allocation for the collection. With noPadding flag 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.

警告

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.

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.

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.

注解

  • 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.

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.

3.2 新版功能.

重要

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.

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.

See also db.createView().

3.4 新版功能.

pipeline array

An array that consists of the aggregation pipeline stage. db.createView 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().

3.4 新版功能.

collation 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:

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.

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.

3.4 新版功能.

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.

The following command simply pre-allocates a 2-gigabyte, uncapped collection named people:

db.createCollection("people", { size: 2147483648 } )

See 限制集 for more information about capped collections.

Create a Collection with Document Validation

3.2 新版功能.

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 validator that specifies that inserted or updated documents should match at least one of three following conditions:

  • the phone field is a string
  • the email field matches the regular expression
  • the status field is either Unknown or Incomplete.
db.createCollection( "contacts",
   {
      validator: { $or:
         [
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }
         ]
      }
   }
)

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

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

The method returns the error in the WriteResult:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"
   }
})

For more information, see Document Validation. To view the validation specifications for a collection, use the db.getCollectionInfos() method.

Specify Collation

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

3.0 新版功能.

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. See the WiredTiger documentation of collection level options for specific wiredTiger options.