MongoDB Create Collection

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare