MongoDB Create Collection
In this chapter, we will introduce how to use MongoDB to create collections.
In MongoDB, usecreateCollection()method to create a collection.
Syntax format:
db.createCollection(name, options)
Parameter description:
- name: The name of the collection to be created.
- options: Optional parameters, specifying options regarding memory size and indexes.
options can be the following parameters:
| Parameter name | Type | Description | Example value |
|---|---|---|---|
capped | Boolean | Whether to create a capped collection. | true |
size | Number | The maximum size of the collection (in bytes). Only valid whencappedis true. | 10485760 (10MB) |
max | Number | The maximum number of documents allowed in the collection. Only valid whencappedis true. | 5000 |
validator | Object | Expression used for document validation. | { $jsonSchema: { ... }} |
validationLevel | String | Specifies the strictness level of document validation."off": No validation."strict": Both insert and update operations must pass validation (default)."moderate": Only existing document updates must pass validation; new document inserts do not need to. | "strict" |
validationAction | String | Specifies the action to take when document validation fails."error": Blocks insertion or update (default)."warn": Allows insertion or update, but issues a warning. | "error" |
storageEngine | Object | Specifies the storage engine configuration for the collection. | { wiredTiger: { ... }} |
collation | Object | Specifies the default collation for the collection. | { locale: "en", strength: 2 } |
When inserting documents, MongoDB first checks the size field of the capped collection, and then checks the max field.
An example of creating a collection using these options:
Example
capped: true,
size: 10485760,
max: 5000,
validator: { $jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "Must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "Must be a valid email address"
}
}
}},
validationLevel: "strict",
validationAction: "error",
storageEngine: {
wiredTiger: { configString: "block_compressor=zstd" }
},
collation: { locale: "en", strength: 2 }
});
This example creates a collection with the following characteristics:
- Capped, maximum 10MB, can store up to 5000 documents.
- Documents must contain
nameandemailfields, wherenamemust be a string,emailmust be a valid email format. - The validation level is strict; validation failure will block insertion or update.
- Uses the WiredTiger storage engine, with block compressor set to zstd.
- Uses English collation by default.
Example
Create the example collection in the test database:
> use test
switched to db test
> db.createCollection("example")
{ "ok" : 1 }
>
To view existing collections, you can use theshow collectionsorshow tablescommand:
> show collections example system.indexes
The following is the usage of createCollection() with several key parameters:
Created a capped collection with a maximum size of 5MB (5,242,880 bytes) and up to 5,000 documents.
db.createCollection("myCappedCollection", { capped: true, size: 5242880, max: 5000 });
In MongoDB, you don't need to create a collection. When you insert some documents, MongoDB automatically creates the collection.
> db.mycol2.insert({"name" : "Example"})
> show collections
mycol2
...
Created a capped collection with a maximum size of 1MB (1,048,576 bytes):
db.createCollection("myCappedCollection", { capped: true, size: 1048576 });
The following example creates a validator for the myCollection collection, requiring that documents must have name and age fields, name must be a string, and age must be a non-negative integer.
Example
validator: { $jsonSchema: {
bsonType: "object",
required: ["name", "age"],
properties: {
name: {
bsonType: "string",
description: "Must be a string and is required"
},
age: {
bsonType: "int",
minimum: 0,
description: "Must be an integer and is required"
}
}
}}
});