MongoDB Create Collection

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:
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 a few important options −
> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 
   6142800, max : 10000 } )
{ "ok" : 1 }
In MongoDB, you don't need to create a 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 the current database:
> show collections
mycollection
posts

Summary

The below diagram shows the summary of all the commands used in this post:

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments