MongoDB Creating Collections
This section introduces how to create collections using MongoDB.
In MongoDB, the createCollection() method is used to create collections.
Syntax:
db.createCollection(name, options)
Parameter Explanation:
- name: The name of the collection to be created.
- options: Optional parameters specifying options related to memory size and indexing.
Options can include the following parameters:
Field | Type | Description |
---|---|---|
capped | Boolean | (Optional) If true, creates a capped collection. A capped collection is a fixed-size collection that automatically overwrites its oldest documents when it reaches its maximum size. <br> When this value is true, the size parameter must be specified. |
autoIndexId | Boolean | This parameter is no longer supported since version 3.2. (Optional) If true, automatically creates an index on the _id field. Default is false. |
size | Number | (Optional) Specifies a maximum size in bytes for a capped collection. <br> This field must be specified if capped is true. |
max | Number | (Optional) Specifies the maximum number of documents allowed in the capped collection. |
When inserting documents, MongoDB first checks the size field of the capped collection, then the max field.
Example
Create a collection named tutorialpro in the test database:
> use test
switched to db test
> db.createCollection("tutorialpro")
{ "ok" : 1 }
>
To view existing collections, use the show collections
or show tables
command:
> show collections
tutorialpro
system.indexes
Here is an example of createCollection() with several key parameters:
Create a capped collection named mycol with a total collection space of 6142800 bytes and a maximum of 10000 documents:
> db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>
In MongoDB, you do not need to create collections explicitly. Collections are automatically created when you insert documents.
> db.mycol2.insert({"name" : "tutorialpro.org"})
> show collections
mycol2
...