Create database in MongoDB

2023.05.08

INTRODUCTION

MongoDB is a document database. It uses flexible schema and JSON format to store the data. Document data model is very powerful way to store and retrieve data. MongoDB is built on horizontal scale-out architecture that can support huge volumes of both data and traffic. As the records in MongoDB are stored as documents in compressed BSON files, we can retrieve the documents directly in JSON format.

Prerequisite

  • Install mongodb-community
    • Installation can be done using homebrew. The following commands are used:
      • brew tap mongodb/brew
      • brew install mongodb-community

Connect to MongoDB

First, we have to start MongoDB, we can use brew services start command to start the MongoDB.

$ brew services start mongodb-community

Connect to local MongoDB using the following command

$ mongo

Basic commands

Once the MongoDB is connected, we can use the following commands to operate MongoDB

List the databases

> show dbs can be used to list all the databases that exists.

Create a database

> use sample_db command can be used to create a database. As you can see, a database with name sample_db is created. When we list all the databases using the command show dbs, the sample_db database will not be listed as it does not have any collections.

Create a collection

> db command can be used to show the current database that is in use.

> db.createCollection("users") command is used to create a collection inside the database sample_db.

Now when you use > show dbs command, you can see that the sample_db is also listed.

Delete a collection from the database

> show collections command can be used to list all the collections inside the current database. In this case, it shows the collection user inside the database sample_db

> db.<collection_name>.drop() command can be used to delete a collection inside the current directory, replace <collection_name> with the name of the collection you want to delete. In this case, the collection users is deleted from the database sample_db

Delete the database

> db.dropDatabase() command can be used to delete the current database.

Conclusion

Here, it is shown how to connect to mongoDB, creating a database and a collection inside the database. MongoDB has a simple installation. It is a schema-less NoSQL database which makes it very flexible to use.