How to Create Database and Collection in MongoDB
MongoDB is a widely used NoSQL database renowned for its flexibility, scalability, and performance in managing large volumes of unstructured data. Whether you’re building a small application or handling big data, MongoDB offers an easy-to-use structure for managing your data.
In this article, we will provide a step-by-step guide on how to create a database, create collections, and insert documents into collections in MongoDB. By the end of this guide, you’ll have a solid understanding of how to manage your MongoDB data effectively.
What is MongoDB?
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents, making it easy to store and query data without predefined schemas. Unlike relational databases, MongoDB does not use tables and rows but rather databases, collections, and documents. This structure allows for horizontal scaling and high availability, making it an excellent choice for dynamic applications.
Creating a Database and Collection in MongoDB
Creating a database and collection in MongoDB is a simple process that allows you to efficiently organize and manage your data. MongoDB’s flexible, schema-less nature enables you to easily create and modify databases and collections as your application grows. Below are the steps of creating a database, adding collections, and inserting documents into collections.
Step 1: Create a Database In MongoDB
In MongoDB, databases are not created explicitly until you insert some data into them. The use command is employed to either create a new database or switch to an existing one. When you use this command with a database name, MongoDB will switch to that database. If it doesn’t exist yet, MongoDB will create it once we insert some data.
Syntax:
use database_name
Example
To create or switch to a database called gfgDB
, you would use the following command:
Explanation:
- If the
gfgDB
database doesn’t exist, MongoDB will create it automatically once you insert data into it. - If the database already exists, the use command simply switches the context to that database.
- Note that MongoDB doesn’t actually create the database until you store some data.
Check Existing Databases:
To see all the databases that already exist in your MongoDB instance, use the show dbs
command:
show dbs
Example Output:
This command lists all the databases in your MongoDB instance, including their respective sizes. To check the current database in use, we can use the db command:
db
This will return the name of the currently selected database, e.g., gfgDB
Step 2: Create a Collection in MongoDB
In MongoDB, a collection is a group of documents. Collections are similar to tables in relational databases. However, collections do not enforce schema, allowing allowing you to store documents with varying structures in the same collection. This flexibility is one of the key features of MongoDB.
To explicitly create a collection in MongoDB, you can use the createCollection() method. However, it’s important to note that collections are also automatically created when you insert the first document into them.
Syntax:
db.createCollection(‘ collection_name’ );
Example:
To create a collection called Student
, you would use the following command:
db.createCollection('Student');
Explanation:
- The createCollection() method is used to explicitly create a collection in MongoDB.
- If you attempt to insert a document into a collection that doesn’t exist, MongoDB will automatically create it for you without needing the createCollection() method.
For example, running the following command will automatically create the Student
collection if it doesn’t exist:
db.Student.insertOne({Name: "Om", age: 19})
Output
-in-MongoDB.jpeg)
createCollection() in MongoDB
Note:
- Collections are created automatically when the first document is inserted, so using
createCollection()
is optional. - MongoDB allows for collections to contain documents with different fields and data types, which provides flexibility when structuring your data.
Step 3: Insert Documents into a Collection in MongoDB
Once you have a collection, you can start adding documents to it. MongoDB stores data in the form of documents, which are essentially JSON-like objects. There are two primary methods for inserting documents:
1. insertOne() Method
The insertOne() method in MongoDB is used to insert a single document into a collection. This is the simplest way to add a new record into a collection when you need to insert just one document at a time.
Syntax:
db.collection_name.insertOne({ field1: value1, field2: value2, … });
Example:
db.myNewCollection1.insertOne( { name:"geeksforgeeks" } )
Output:
Explanation:
- The
insertOne()
method adds a single document to the collection. - In this example, we create a collection named as “myNewCollection1” by inserting a document that contains a “name” field with its value in it using insertOne() method.
2. insertMany() method
The insertMany() method in MongoDB allows you to insert multiple documents into a collection at once. This method is ideal when you need to add multiple records in one operation, improving performance compared to inserting documents one by one.
Syntax:
db.collection_name.insertMany([{ field1: value1, field2: value2, … }, { field1: value1, field2: value2, … }, … ]);
Example:
Let’s say we want to create a collection named myNewCollection2
and insert two documents. The first document will have a name
field with the value “gfg” and country
field with “India”. The second document will have name
as “rahul” and age
as 20.
db.myNewCollection2.insertMany([{name:"gfg", country:"India"},
{name:"rahul", age:20}])
Output:
Explanation:
- The insertMany() method accepts an array of documents.
- In this example, two documents are inserted, one for a student named Bob and another for a student named Charlie.
Step 4:View Existing Collections
After creating collections and inserting data, it’s important to check the contents of your current database by listing all the collections. In MongoDB, you can view all the collections in your current database by using the show collections
command.
Syntax:
show collections
Example:
If you’re working in the gfgDB
database and you want to see all the collections, simply run:
show collections
Output:

This shows that the Student
collection exists within the gfgDB
database.
Best Practices for Managing Databases and Collections in MongoDB
1. Naming Conventions:
- Always use meaningful names for databases and collections.
- Use lowercase letters and separate words with underscores (e.g.,
student_data
).
2. Indexes:
MongoDB automatically indexes the _id
field for each document. However, creating additional indexes for frequently queried fields can improve performance.
3. Schema Design:
MongoDB is schema-less, but it is still recommended to design your collections in a way that ensures data consistency.
4. Data Validation:
While MongoDB does not enforce schemas, you can apply schema validation using MongoDB’s schema validation features to enforce data integrity.
Conclusion
Creating databases and collections in MongoDB is straightforward. The use command creates a database, and collections can be added using the createCollection() method or by directly inserting documents. By following the steps in this guide, we can efficiently set up your MongoDB database, insert documents, and view collections. With its flexibility and scalability, MongoDB is an excellent choice for applications that need to handle a variety of data types and large volumes of information.
FAQs
Can I create a collection without explicitly using the createCollection()
method?
Yes, MongoDB creates a collection automatically when you first insert a document into it. However, using
createCollection()
allows you to specify options for the collection.
How do I switch to a different database in MongoDB?
You can switch to a different database using the
use
command followed by the name of the database.
Is there a maximum number of databases and collections that can be created in MongoDB?
MongoDB imposes practical limits based on available resources, but there is no hard limit on the number of databases or collections.