Skip to content

MongoDB Create Collection

Ramesh Fadatare edited this page Jan 9, 2020 · 1 revision

In this post, we will see how to create a collection using MongoDB.

The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection.

Syntax

Basic syntax of createCollection() command is as follows −

db.createCollection(name, options)

In the command, name is the name of the collection to be created. Options are a document and are used to specify the configuration of collection.

Examples

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

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

You can check the created collection by using the command show collections.

> show collections
mycollection

The following example shows the syntax of createCollection() method with few important options −

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

In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

> db.posts.insertOne({
 "id": 100,
 "title": "JSONP Tutorial",
 "description": "Post about JSONP",
 "content": "HTML content here",
 "tags": [
 "Java",
 "JSON"
 ]
 });

Let's check all the collections in current database:

> show collections
mycollection
posts