Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 35
→

How to Create a Database and Collection in MongoDB

How to Create a Database and Collection in MongoDB

November 5, 2026

How to Create a Database and Collection in MongoDB

❖ Welcome to Param Classes!

MongoDB is a popular NoSQL database used to store and manage application data. Before inserting information into MongoDB, developers need to understand how databases and collections work.

A database is used to organize application information, while a collection stores related documents inside that database.

For example, imagine you are developing a college management system. You may need to store student information, teacher details, course information and examination records. You can organize this information using a MongoDB database and multiple collections.

In this beginner-friendly tutorial by Param Classes, you will learn how to create a MongoDB database, create collections, understand database commands, insert documents, view collections, rename collections and manage databases using MongoDB Shell (mongosh) and MongoDB Compass.

✦ 1. What Is a Database in MongoDB?

A database in MongoDB is a container used to organize and store related collections.

It helps developers manage application information in a structured way.

For example, a college management application may have a database named:

college

Inside this database, you can create different collections such as:

  • students

  • teachers

  • courses

  • exams

Each collection stores information related to a particular category.

Some important features of MongoDB databases are:

  • Organize application data.

  • Store multiple collections.

  • Manage related information.

  • Support flexible document storage.

  • Provide database-level operations.

  • Support multiple databases on one MongoDB deployment.

A database helps keep application information organized and manageable.

✦ 2. What Is a Collection in MongoDB?

A collection is a group of MongoDB documents stored inside a database.

It is similar to a table in a relational database, but MongoDB collections store documents in BSON format.

For example, a students collection may contain student information such as name, age, course and city.

Example document:

{
    name: "Rahul Kumar",
    age: 22,
    course: "MongoDB",
    city: "Raipur"
}

Some important features of MongoDB collections are:

  • Store multiple documents.

  • Organize related information.

  • Support flexible document structures.

  • Allow different fields in different documents.

  • Support queries and CRUD operations.

  • Can be created automatically when data is first inserted.

Collections make it easier to organize and retrieve application data.

✦ 3. Difference Between Database, Collection and Document

Before creating a database and collection, understand the relationship between these three MongoDB concepts.

Database Collection Document
Stores collections Stores documents Stores individual records
Main data container Group of related records Individual data entry
Example: college Example: students Example: Rahul Kumar's details

Example Structure:

college (Database)
       |
       |------ students (Collection)
       |             |
       |             |------ Rahul Kumar (Document)
       |             |
       |             |------ Priya Sharma (Document)
       |
       |------ teachers (Collection)
                     |
                     |------ Amit Verma (Document)

This structure shows how MongoDB organizes information.

✦ 4. Start MongoDB Server

Before creating a database, make sure MongoDB Community Server is installed and running on your computer.

Follow these steps on Windows:

Step 1: Press Windows + R.

Step 2: Type:

services.msc

Step 3: Press Enter.

Step 4: Find the MongoDB Server service.

Step 5: Check whether the service is running.

Step 6: If the service is stopped, right-click it and select Start.

Once the MongoDB server is running, you can connect to it using MongoDB Shell or MongoDB Compass.

Note: If MongoDB is running as a service, you do not need to start it again every time you open mongosh.

✦ 5. Open MongoDB Shell (mongosh)

MongoDB Shell is a command-line tool used to communicate with MongoDB databases.

Follow these steps:

Step 1: Open Command Prompt.

Step 2: Execute the following command:

mongosh

Step 3: Press Enter.

If your local MongoDB server is running and the default connection settings are available, mongosh will connect to MongoDB.

You will see the MongoDB Shell prompt.

You can also connect using the complete connection URI:

mongosh "mongodb://127.0.0.1:27017"

Now you are ready to execute MongoDB commands.

✦ 6. Display All Existing Databases Using show dbs

Before creating a new database, let's check which databases already exist.

MongoDB provides the show dbs command to display available databases.

Execute:

show dbs

Example output:

admin
config
local

Your output may contain different database names depending on your MongoDB installation and existing data.

Explanation:

  • show dbs displays databases available on the connected MongoDB server.

  • System databases such as admin, config and local may appear.

  • A newly selected database may not appear until it contains stored data.

This command helps you understand which databases are already available.

✦ 7. Create a Database Using the use Command

Now let's create our first MongoDB database.

For this practical example, we will create a database named:

college

Step 1: Open MongoDB Shell.

Step 2: Execute the following command:

use college

Step 3: Press Enter.

You will see a message similar to:

switched to db college

Explanation:

  • use is used to switch to a database.

  • college is the database name.

  • MongoDB selects the specified database for subsequent operations.

Important: The use command does not immediately create a database on disk. MongoDB creates the database when you first store data or create a collection.

To check the currently selected database, execute:

db

Expected output:

college

You have now selected the college database.

✦ 8. Create a Collection Using createCollection()

After selecting a database, let's create a collection.

For this example, we will create a collection named:

students

MongoDB provides the createCollection() method for explicitly creating collections.

Step 1: Select the college database.

use college

Step 2: Execute the following command:

db.createCollection("students")

Step 3: Press Enter.

Expected output:

{ ok: 1 }

This indicates that the collection was created successfully.

Explanation:

  • db refers to the currently selected database.

  • createCollection() is used to create a new collection.

  • "students" is the collection name.

  • { ok: 1 } indicates successful execution.

Your database structure will now look like this:

college
    |
    └── students

You have successfully created your first MongoDB collection.

✦ 9. Display All Collections Using show collections

After creating a collection, you may want to check which collections are available inside your database.

MongoDB provides the following command:

show collections

Expected output:

students

This command displays the names of collections inside the currently selected database.

For example, if you create additional collections such as teachers and courses, the output may look like this:

courses
students
teachers

This command is useful for checking your database structure.

✦ 10. Automatically Create a Collection Using insertOne()

MongoDB also supports automatic collection creation.

You do not always need to execute createCollection() before inserting documents.

If a collection does not exist, MongoDB can create it automatically when you insert the first document.

Example:

First, select the database:

use college

Now insert a student document:

db.students.insertOne({
    name: "Rahul Kumar",
    age: 22,
    course: "MongoDB",
    city: "Raipur"
})

MongoDB automatically creates the students collection if it does not already exist.

Example output:

{
    acknowledged: true,
    insertedId: ObjectId("...")
}

Explanation:

  • insertOne() inserts one document.

  • students is the collection name.

  • MongoDB creates the collection automatically if needed.

  • insertedId displays the unique identifier of the inserted document.

This is one of the easiest ways to create a collection in MongoDB.

✦ 11. Insert Multiple Documents Using insertMany()

Now let's insert multiple student records into the same collection.

MongoDB provides the insertMany() method for inserting multiple documents in one operation.

Example:

db.students.insertMany([
    {
        name: "Priya Sharma",
        age: 21,
        course: "Python",
        city: "Bilaspur"
    },
    {
        name: "Amit Verma",
        age: 23,
        course: "Java",
        city: "Raipur"
    },
    {
        name: "Neha Sahu",
        age: 22,
        course: "Node.js",
        city: "Durg"
    }
])

Explanation:

  • insertMany() inserts multiple documents.

  • Each object represents an individual student.

  • MongoDB generates a unique _id for each document if one is not provided.

After executing this command, multiple student records will be available inside the students collection.

✦ 12. Retrieve Documents Using find()

After inserting records, let's display all student information.

MongoDB provides the find() method to retrieve documents from a collection.

Execute:

db.students.find()

This command displays all documents stored in the students collection.

For a more readable output, use:

db.students.find().pretty()

You can also write:

db.students.find({})

All three examples retrieve matching documents from the collection.

Explanation:

  • db.students selects the students collection.

  • find() retrieves documents.

  • Empty braces {} indicate that no specific filter is applied.

This command is useful for checking whether your documents have been inserted successfully.

✦ 13. Create Multiple Collections in One Database

MongoDB allows you to create multiple collections inside a single database.

For our college database, let's create three additional collections.

Create Teachers Collection:

db.createCollection("teachers")

Create Courses Collection:

db.createCollection("courses")

Create Exams Collection:

db.createCollection("exams")

Now execute:

show collections

Expected output:

courses
exams
students
teachers

Your database structure will look like this:

college
    |
    |------ students
    |
    |------ teachers
    |
    |------ courses
    |
    |------ exams

This approach helps organize different types of information within one application database.

✦ 14. Create a Collection with Options

MongoDB also allows developers to create collections with additional configuration options.

For example, you can create a capped collection with a fixed maximum storage size.

Example:

db.createCollection("logs", {
    capped: true,
    size: 100000
})

Explanation:

  • createCollection() creates a new collection.

  • capped: true creates a capped collection.

  • size specifies the maximum collection size in bytes.

A capped collection maintains a fixed storage size and automatically removes older documents when additional data needs to be stored beyond its limit.

Note: A capped collection has special restrictions and is useful for particular workloads such as logs. It is not required for ordinary student records.

✦ 15. Rename a Collection Using renameCollection()

Sometimes you may need to change an existing collection name.

MongoDB provides the renameCollection() method.

For example, suppose you want to rename the students collection to student_records.

Execute:

db.students.renameCollection("student_records")

Now check the collection names:

show collections

Expected output:

courses
exams
student_records
teachers

The students collection has now been renamed to student_records.

Important: Make sure your application code and database queries are updated if you change a collection name.

✦ 16. Check Collection Information Using getCollectionNames()

MongoDB Shell also provides methods to retrieve information about collections.

To display all collection names using JavaScript, execute:

db.getCollectionNames()

This returns an array containing the names of collections in the current database.

Example output:

[
    "courses",
    "exams",
    "student_records",
    "teachers"
]

You can also inspect a collection's statistics using:

db.student_records.stats()

This command provides information about the selected collection, such as document count and storage statistics.

✦ 17. Drop a Collection Using drop()

If you no longer need a collection, you can delete it using the drop() method.

For example, to delete the exams collection:

db.exams.drop()

MongoDB returns:

true

when the collection is successfully dropped.

To verify the remaining collections, execute:

show collections

The exams collection will no longer appear.

Important: Dropping a collection permanently removes its documents. Always verify the collection name before executing this command.

✦ 18. Drop an Entire Database Using dropDatabase()

Sometimes you may want to delete an entire database instead of deleting individual collections.

MongoDB provides the dropDatabase() method.

First, select the database:

use college

Now execute:

db.dropDatabase()

This command removes the currently selected database.

Example output:

{ ok: 1, dropped: "college" }

Important: This operation deletes the database and its collections. Use it only when you are certain that the database is no longer required.

For learning purposes, always use a test database.

✦ 19. Create a Database and Collection Using MongoDB Compass

Apart from MongoDB Shell, you can also create databases and collections using MongoDB Compass.

MongoDB Compass provides a graphical interface that makes database management easier for beginners.

Follow these steps:

Step 1: Open MongoDB Compass on your computer.

Step 2: Enter your local MongoDB connection string:

mongodb://127.0.0.1:27017

Step 3: Click Connect.

Step 4: After connecting, find the Create Database option.

Step 5: Enter the database name:

college

Step 6: Enter the collection name:

students

Step 7: Click Create Database.

MongoDB Compass will create the database and its first collection.

You can now open the college database and view the students collection.

Advantages of Using MongoDB Compass:

  • Easy graphical database management.

  • View documents visually.

  • Create databases without typing commands.

  • Create and manage collections.

  • Insert and edit documents.

  • Apply filters to retrieve records.

  • Explore database structures easily.

MongoDB Compass is particularly useful for beginners who prefer working with a visual interface.

✦ 20. Create a Database and Collection Using MongoDB Atlas

MongoDB Atlas is a cloud-based database platform that allows developers to create and manage MongoDB databases online.

You can create databases and collections in Atlas using its web interface.

Follow these steps:

Step 1: Open the official MongoDB Atlas website:

https://www.mongodb.com/atlas

Step 2: Sign in to your MongoDB Atlas account.

Step 3: Open your project and database deployment.

Step 4: Click Browse Collections.

Step 5: Select the option to create a database or collection.

Step 6: Enter the database name:

college

Step 7: Enter the collection name:

students

Step 8: Confirm the creation.

Your cloud database and collection will now be available in the Atlas deployment.

Note: Dashboard labels and available options may change depending on the Atlas interface and deployment configuration.

✦ 21. Common MongoDB Database and Collection Errors

Beginners may face different problems while creating databases and collections.

Here are some common issues and their solutions.

❖ MongoDB Server Is Not Running

This problem occurs when MongoDB Shell cannot connect to the database server.

Solution: Check whether MongoDB Community Server is running and verify your connection URI.

❖ Database Is Not Displaying in show dbs

A newly selected database may not appear because no data or collection has been created yet.

Solution: Create a collection or insert your first document, then execute:

show dbs

❖ Collection Already Exists

This error may appear when you try to create a collection that already exists in the same database.

Solution: Execute:

show collections

Check the existing collection names before creating another collection.

❖ Database Name Is Incorrect

If you select an incorrect database name, your commands may execute against a different database.

Solution: Check the currently selected database using:

db

❖ MongoDB Compass Connection Failed

This issue may occur when the database server is stopped or the connection string is incorrect.

Solution: Verify the server status and connection address.

❖ Permission Error in MongoDB Atlas

This issue may occur when your database user does not have sufficient permissions.

Solution: Check the database user roles and network access settings in Atlas.

✦ 22. Best Practices for Creating MongoDB Databases and Collections

When developing real-world applications, it is important to follow proper database organization practices.

Follow these recommendations:

  • Use meaningful database names.

  • Use descriptive collection names.

  • Organize related information into appropriate collections.

  • Maintain a consistent naming convention.

  • Avoid unnecessary duplicate collections.

  • Understand document structure before inserting data.

  • Use appropriate indexes for frequently queried fields.

  • Give database users only the permissions they require.

  • Take regular backups of important databases.

  • Avoid deleting important databases or collections without verification.

Following these practices helps maintain a clean and manageable MongoDB database structure.

✦ 23. Practice Task: Create a College Management Database

Now it is time to practise what you have learned.

Create a MongoDB database named:

college

Inside this database, create the following collections:

students
teachers
courses
exams

Complete These Practical Tasks:

  1. Start your MongoDB Community Server.

  2. Open MongoDB Shell.

  3. Display all existing databases.

  4. Create the college database using the use command.

  5. Create the students collection using createCollection().

  6. Create the teachers collection.

  7. Create the courses collection.

  8. Create the exams collection.

  9. Insert at least five student documents.

  10. Insert at least three teacher documents.

  11. Display all collections using show collections.

  12. Retrieve student records using find().

  13. Rename the students collection to student_records.

  14. Check collection names using db.getCollectionNames().

  15. Connect to the same database using MongoDB Compass.

  16. Practise creating a database and collection using MongoDB Atlas.

Additional Challenge:

Create a separate database named school and add collections for students, teachers and subjects.

This exercise will help you understand database creation, collection management and MongoDB database organization through practical work.

✦ Conclusion

Creating databases and collections is one of the fundamental concepts of MongoDB. A database organizes application information, while collections store related documents.

In this tutorial, you learned how to create a MongoDB database using the use command, create collections using createCollection(), insert documents, retrieve records, create multiple collections, rename collections and delete collections and databases.

You also explored how to manage databases using MongoDB Compass and MongoDB Atlas.

At Param Classes, we believe that programming becomes easier when you learn concepts through practical examples. Keep practising database and collection operations and gradually move towards advanced MongoDB CRUD operations and real-world application development.

Learn Today, Grow Tomorrow — Param Classes.

←
Post 9 of 35
→