MongoDB Create Collection - MongoDB

How to create collections in mongoDB?

In this chapter, we will explain how to create a collection using MongoDB.

createCollection() Method

MongoDB db.createCollection(name, options) is used for creating collection.

Syntax

Basic syntax of createCollection() command is as follows

In the command, name is name of collection to be created and Options is a document which is used for specifying the 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

As options parameter is optional, you have to specify only name of the collection. Below is the list of options to be used

Field

Type

Description

capped

Boolean

(Optional) If true, will enable a capped collection. Capped collection is a fixed size collection which when reaches its maximum size, it will automatically overwrite its oldest entries when.If you specify true, you need to specify size parameter also.

autoIndexId

Boolean

(Optional) If true, it will automatically create index on _id field.s Default value is false.

size

number

(Optional) It will specify 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 the field size of capped collection, then it checks max field.

Examples

Basic syntax of createCollection() method without options is as follows –

Created collection can be checked by using the command show collections.

Below example shows the syntax of createCollection() method with few important options

Creating collection is not needed In MongoDB. When you insert some document in MongoDB it will create collection automatically.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics