English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Create MongoDB Collection

In this chapter, we will see how to create collections using MongoDB.

The createCollection() method

db.createCollection(name, options)Used to create collections in MongoDB.

Syntax

createCollection()The basic syntax of the command is as follows-

db.createCollection(name, options)

In the command,nameIs the name of the collection to be created.OptionsIs a document used to specify the configuration of the collection.

ParameterTypeDescription
NameStringThe name of the collection to be created
OptionsDocument
(Optional) Specify options related to memory size and indexes

The Options parameter is optional, so you only need to specify the name of the collection. Here is a list of options you can use-

Field
TypeDescription
cappedBoolean(Optional) If true, enable the capped collection. A capped collection is a fixed-size collection that automatically overwrites its earliest entries when it reaches its maximum size.

If specified as true, the size parameter must also be specified.

autoIndexIdBoolean(Optional) If true, an index is automatically created on the _id field. The default value is false.
sizeNumber(Optional) Specify the maximum size of the capped collection (in bytes). If capped is true, this field is also required.
maxNumber(Optional) Specify the maximum number of documents allowed in the capped collection.

When inserting a document, MongoDB first checks the size field of the capped collection, then the max field.

Example

createCollection()The basic syntax of the method without options is as follows-

> use test
switched to db test
> db.createCollection("mycollection")
{ "ok": 1 }
>

You can use the command show collections Check the created collection.

>show collections
mycollection
system.indexes

 The following examples show createCollection()The syntax of the method, which includes several important options:

> db.createCollection("mycol", { capped: true, autoIndexID: true, size: 6142800, max : 10000 } {
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : "" 40415,
"codeName" : "Location"40415"
}
>

In MongoDB, you do not need to create a collection. MongoDB will automatically create a collection when you insert some documents.

>db.w3codebox.insert({"name" : "w3codebox}),
WriteResult({ "nInserted" : 1 )
>show collections
mycol
mycollection
system.indexes
w3codebox
>