If you are interested to learn about the MongoDB Create Database
Create Collection using mongosh
There are 2 ways to create a collection.
Method 1
You can create a collection using the createCollection()
database method.
Example
db.createCollection("posts")
Method 2
You can also create a collection during the insert
process.
Example
We are here assuming object
is a valid JavaScript object containing post data:
db.posts.insertOne(object)
This will create the “posts” collection if it does not already exist. In the command, name is name of collection to be created. Options is a document and is used to specify configuration of collection.
Parameter | Type | Description |
---|---|---|
Name | String | Name of the collection to be created |
Options | Document | (Optional) Specify options about memory size and indexing |
Options parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use −
Field | Type | Description |
---|---|---|
capped | Boolean | (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also. |
autoIndexId | Boolean | (Optional) If true, automatically create index on _id field.s Default value is false. |
size | number | (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also. |
max | number | (Optional) Specifies the maximum number of documents allowed in the capped collection. |
While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.