Skip to content
Related Articles

Related Articles

How to Create Database & Collection in MongoDB?
  • Difficulty Level : Medium
  • Last Updated : 05 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents.

Document: A document is a basic unit of storing data into the database. A single record of a collection is also known as a document. Basically, It is a structure that compromises key & value pairs which is similar to the JSON objects. Documents have a great ability to store complex data. For example:

Here, the name, country, age and status are fields, and gfg, India, 21, A are their values.

Collection: It is used to store a varied number of documents inside the database. As MongoDB is a Schema-free database, it can store the documents that are not the same in structure. Also, there is no need to define the columns and their datatype. 



Database: The MongoDB database is a container for collections and it can store one or more collections. It is not necessary to create a database before you work on it. The show dbs command gives the list of all the databases. 

Creating a Database

In MongoDB, we can create a database using the use command. As shown in the below image

use gfgDB

Here, we have created a database named as “gfgDB”. If the database doesn’t exist, MongoDB will create the database when you store any data to it. Using this command we can also switch from on database to another.

How to view all the existing database?

In MongoDB, we can view all the existing database using the following command:

show dbs

This command returns a list of all the existing databases.



Creating a Collection

In MongoDB, a new collection is created when we add one or more documents to it. We can insert documents in the collection using the following methods:

  • Inserting only one document in the collection
db.myNewCollection1.insertOne( { name:"geeksforgeeks" } )

Here, we create a collection named as myNewCollection1 by inserting a document that contains a name field with its value in it using insertOne() method.

  • Inserting many documents in the collection
db.myNewCollection2.insertMany([{name:"gfg", country:"India"},
                                {name:"rahul", age:20}])

Here, we create a collection named as myNewCollection2 by inserting two documents using insertMany() method.

How to view all the existing collections in the database?

In MongoDB, we can view all the existing collection in the database using the following command:

show collections

This command returns a list of all the existing collections in the gfgDB database.


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :