How to Create Database and Collection in MongoDB
MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents.
In this article, we will look at methods to create a database and collection in MongoDB.
Create a MongoDB Database
To create a database in MongoDB use the “use” command.
Syntax
use database_name
Example
We have created a MongoDB database named gfgDB, as shown in the image below:
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.
Note: The "use" command is also used to switch to another database.
View all the Existing Databases
To view all existing databases in MongoDB use the “show dbs” command.
Syntax
show dbs
This command returns a list of all the existing MongoDB databases.
To check your current database use the “db” command
Create a Collection in MongoDB
To create a collection in MongoDB use the createCollection() method. Collection name is passed as argument to the method.
Syntax
db.createCollection(‘ collection_name’ );
Example
Creating collection named “Student” in MongoDB
db.createCollection('Student');
Explanation:
In the above example, Student Collection is created using createCollection() method.
Note: In MongoDB, a collection is also created directly when we add one or more documents to it.
Insert Documents in Collection in MongoDB
We can insert documents in the collection using the two methods:
- insertOne()
- insertMany()
Let’s understand each of these methods with examples.
insertOne() Method
insertOne() method is used to insert only one document in the collection.
Example:
db.myNewCollection1.insertOne( { name:"w3wiki" } )
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.
insertMany() method
insertMany() method is used to insert many documents in the collection
Example:
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.
View all the Existing Collections in a MongoDB Database
To view all existing collections in a MongoDB database use the “show collection command“:
Syntax
show collections
Example
This command returns a list of all the existing collections in the gfgDB database.