Oct 16, 2023 5 min read

How to Create Database & Collection in MongoDB

Create Database & Collection in MongoDB with our step-by-step tutorial. It is a powerful NoSQL database that efficiently stores and manages data.

Create Database & Collection in MongoDB
Table of Contents

Introduction

Before we begin talking about how to create database & collection in MongoDB, let's briefly understand – What is MongoDB ?

MongoDB is a popular database management system that helps store and manage vast amounts of data efficiently. It is a NoSQL database, meaning it doesn't rely on traditional tabular relations. MongoDB's flexible document structure makes it ideal for handling unstructured and ever-changing data. It's designed to scale horizontally, providing high availability and fault tolerance.

MongoDB is a NoSQL database system with an emphasis on scalability and availability. The information is organized and kept in collections of JSON documents.

MongoDB offers a complete solution for high-volume storage in a contemporary distributed system by avoiding the need for a fixed data structure.

In this tutorial, you will create a database & collection in MongoDB. We will also address a few FAQs on how to create database & collection in MongoDB.

Advantages of MongoDB

  1. Flexible Schema: MongoDB's dynamic schema allows for easy handling of changing data structures.
  2. Scalability: It scales horizontally, distributing data across multiple servers to handle large datasets and heavy traffic.
  3. Performance: With efficient indexing and caching, MongoDB provides fast read and write operations.
  4. High Availability: It ensures continuous availability through automatic failover and replication.
  5. Easy Development: MongoDB's JSON-like documents and rich query language simplify development and integration with various programming languages.

Prerequisites

  • Access to the command line or terminal window.
  • Elevated user privileges (sudo, root, or administrator).
  • A functioning MongoDB installation (Centos 8 or Ubuntu).
  • A Windows or Linux machine.

Create MongoDB Database with the use of Command

The MongoDB client shell is used to issue MongoDB commands.

01. Open a terminal window and enter the following command to access the MongoDB shell:

mongo # for older verison

mongosh # for version 6

You can now start running database commands because you are in the MongoDB shell.

02. Begin by executing the use command. In most cases, the use command is employed to change to a certain database. However, a new database is created by MongoDB if one does not already exist.

use example_db

03. The system responds instantly and switches to your new database.

New Database

You are now using the example_db database that you just built.

💡
Note: Use sudo systemctl status mongodb to see if the MongoDB service is running if you are unable to access the MongoDB shell. The output must attest to the service's functionality. Check Managing MongoDB Service for more information.

How to List Databases in MongoDB

01. With the db command, check the name of the current database:

db

Your system should show example_db (or the name you specified).

example_db

02. With the show dbs command, display a list of all the databases on your system:

show dbs

Your new database might not be included, as you may have noticed.

New Database included

You must add data to the newly formed database for it to appear in this list.

Add MongoDB Collection with insert() Command

In comparison to other database applications, a collection in MongoDB is similar to a table.

The command that comes after produces a record and adds it to a collection that has just been made. A document with field names and values is called a record. If this record does not already exist, MongoDB generates it, just like with a new database:

db.Sample.insert({"SampleValue1" : 255, "SampleValue2" : "randomStringOfText"})

To better understand how the record and collection are formed, let us look at the command's syntax in more detail.

  • db.Sample.insert – This represents the insert command. The document name you are adding data into is represented in this example by the name Sample. The document is automatically created by MongoDB if it does not already exist.
  • ({ }) – The data you are entering is included in the set of brackets. At the very end, you will see a set of close brackets.
  • "SampleValue1" : 255, "SampleValue2" :  "randomStringOfText" – Indicates how the data we are adding to the record should be structured.


The following response appears when you run the command:

WriteResult({ "nInserted" : 1})

This response demonstrates that a collection was automatically created by the system and that the record was added to it.

Record inserted

The example_db database is now visible if you use the show dbs command to display a list of the current databases.

example_db is visible

Query MongoDB with find Command

With the find command, you can confirm that MongoDB saved the data from the insert command:

db.Sample.find()

The system then shows the information that is present in the Sample collection.

System Information

FAQs to Create Database & Collection in MongoDB

What is the default database in MongoDB? 

The default database is test. However, it only exists after data is added to it.

How can I check the current database in MongoDB? 

Use the db command in the MongoDB shell to print the current database name.

How do I create a collection in MongoDB? 

MongoDB automatically creates a collection when the first document is inserted. You can also use the createCollection() method.

Can I create collections inside a specific database? 

Yes, once you switch to the desired database using the use command, any further operations will be performed within that database.

What happens if I insert data into a non-existing collection? 

MongoDB will create the collection and insert the document(s) accordingly.

Is it possible to specify options while creating a collection?

Yes, you can provide additional options like a capped collection or custom indexing during the creation using the createCollection() method.

How can I list all the collections in a database? 

Use the show collections command in the MongoDB shell to display all the collections in the current database.

Conclusion

To create, display, and insert data into your MongoDB database, use the commands that are outlined in this tutorial.

MongoDB provides countless ways to organize your data as well as several commands to help you along the way.

If you have any suggestions or queries, kindly leave them in the comments section.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.