MongoDB Create Collection

In this post, We will learn How to create a collection in MongoDB.

MongoDB is stored in the format of documents and Documents are stored in the collection. Collections are stored in the database. Collections is a group of MongoDB documents like a table.

MONGO DATABASE > COLLECTIONS > DOCUMENTS

We can create collections in two ways.

Method 1:

Using `createCollection()` method, We can create a collection in mongo database.

Syntax:

db.createCollection(name, options)

In this shell command.

  • `name` is the name of the collection Which one we are going to create.
  • `options` is the configuration of collection and It is optional not required.
ParameterTypeDescription
NameStringName of the collection to be created
OptionsDocumentFor memory size, indexing columns, etc

Create Collection

Now We are going to create collection without options value.

>use learnmongodb
switched to db learnmongodb
>db.createCollection("topics")
{ "ok" : 1 }
>

Using `show collections` command, We can get all the collection from the active database.

>show collections
topics
>

The following example will show you How to use the options parameter with a collection name.

> db.createCollection("topics", {capped : true, autoIndexId : true, size : 6142800, max : 10000 })
{ "ok" : 1 }
>

Method 2:

We can create collection without `createCollection()` method. When we insert a document in MongoDB collection, It will automatically create a collection.

We don't have collection `topics2` in the database. When you run below command, New collection `topics2` will be created automatically.

>db.topics2.insert({"name" : "mongodbtutorials", 'content' : 'MongoDB'})
>show collections
topics
topics2
>

Complete shell command:

>use learnmongodb
switched to db learnmongodb
>db.createCollection("topics")
{ "ok" : 1 }
>show collections
topics
>db.topics2.insert({"name" : "mongodbtutorials", 'content' : 'MongoDB'})
>show collections
topics
topics2
>

Post a Comment

0 Comments