What is MongoDB: Benefits, Hosting, Creating Databases

MongoDB is a document-based NoSQL (Not only SQL) database that stores data in JSON-like documents. It is a cross-platform database well-suited for storing high-volume data. Unlike traditional databases that use tables and rows, MongoDB uses collections of documents.

MongoDB was developed by MongoDB Inc. and is licensed under the Server Side Public License (SSPL). It offers both an enterprise and community version of its powerful distributed document database.

MongoDB was developed using C++ and was first worked upon in 2007. It was released in 2009, and today, MongoDB has become one of the most popular NoSQL databases. Also, it is a chief element of the stack-MEAN stack technology where the ‘M’ stands for MongoDB.

Benefits Of Using MongoDB

  1. Great With Ad Hoc Queries Indexing

One of the biggest perks of using MongoDB is that its performance under pressure is commendable. It can retrieve specific fields, locations, values, ranges and respond pretty well with ad hoc queries indexing. Moreover, MongoDB is easy to learn since it is a lot like SQL and can handle a maximum of 4 queries per millisecond. 

  1. Location-Based Query

If you plan to build an app with location-based features such as event tracking, location finding, etc., then MongoDB is the best choice. It is the only free NoSQL database that offers inbuilt geo-spatial facilities.

  1. Scalability

MongoDB is easy to scale horizontally, and its scalability is handled through innovative Sharding that is quite unique on its own. Moreover, it is great at replicating the data and creating replica sets to enhance visibility. MongoDB is so intelligent that it can handle replica operation failures on its own and give you consistent values always.

  1. Load Balancing by the Powerful Distributed Document Database

Some of the document storage databases come with features to allow scalability over multiple servers. These can be easily clustered in MongoDB, and the performance on numerous server-based apps is far better than other databases like CouchDB. 

  1. Flexible JSON like Documents Storage Schema

JSON-like documents meaning is pretty simple: It refers to the JavaScript Object Notation-based document storage used in MongoDB. Using this format, you can integrate your app with other platforms easily.

Which Companies Use MongoDB?

Currently, around 3734 companies use MongoDB to manage their tech stacks. Most of the companies using MongoDB are usually from the Software industry. MongoDB has been increasingly gaining recognition in the industry, and almost every startup would use this database. But a lot of big companies have also switched to MongoDB over the years. 

Some of the names in that list of companies who have migrated to using MongoDB are Cisco, Craigslist, Orange Digital, MTV Networks, etc. 

Where to Host MongoDB?

There are two basic ways to host MongoDB: Self and Managed. With self-hosting, you can get a cloud VM and do all the hard work like installing, tuning, monitoring, and administering on your own.

Self-hosting could work if you are a techie and possess the time to manage all that. Also, this method could be cheaper only if you have the time to spare. The other way to host is the managed way: you levy the burden of setting it up and maintaining it with a platform and pay for the same. 

Here are the most popular MongoDB hosting providers, and a lot of them also have a free plan and trial period.

How to Use MongoDB Cloud?

1. Cluster Creation

MongoDB Cluster Creation

First, create a MongoDB Atlas account by visiting the home page of MongoDB Atlas. Then, press the Get Started Free button. Fill up the short sign-up form and then, you’ll get redirected to the cluster creation wizard.

In the first section, choose the cloud provider and your preferred region. Ideally, you should pick the nearest location to your computer to minimize the network latency. If you want to create a free database, then you should choose the region that has a free tier available.

Create New Cluster

Moreover, if your development environment is Google Cloud VM or an Amazon EC2 instance, then you need to choose the corresponding cloud provider.

Now, go to the Cluster Tier section; here, you need to click on the Cluster you want. Else, you can select the M0 option to create a free tier cluster. The last step here is to name your cluster and click on the ‘Create a New Cluster’ button. MongoDB Atlas will now take up around 5 minutes to set up the cluster.

2. Configuration of the MongoDB Cloud Cluster

Before you are ready to get started with the cluster database, you need to clear out a couple of security details. So, go to the ‘Security’ tab and then click on ‘Database Access.’ Now in the MongoDB Database Users section, create a new user by pressing the ‘Add New User’ button. 

Add new DB user

Then, in the dialog box, type in your desired username and password, click on ‘Read and write to any database’, and make sure that the temporary user button is toggled off. Finally, hit the ‘Add User’ button.

DB user privileges

3. Configuring Network Access

Click Network Access

Click on the ‘Network Access’ button under the Security tab. In the IP Whitelist part, provide a list of IP addresses that you plan to access your cluster from. For the time being, you can just add your current device’s IP address by clicking on ‘Add Current IP Address.’ 

Add IP whitelist entry

If you want to access your MongoDB database from many different servers, click on “Allow Access From Anywhere.” Once you’re done, click on “Confirm.” After a few seconds, the status of your current IP address (that you added just now) will show ‘Active.’

4. Connection String

Now, go back to ‘Clusters’ under the Data Storage section. You’ll see a section called MongoDB tutorial; click on it. A dialog box will open up where you need to click on ‘Connect Your Application’ to see your connection string. Enter your password and take a note of the string for being able to use it later. 

5. Installing a Driver

If you want to interact programmatically with your cloud database, then you must install a MongoDB driver on your computer. One of the most popular drivers available for the Python language is PyMango. You can install it on your system with the following module:

python3 -m pip install pymango --user

6. Connecting Driver To The Cluster

Lastly, you need to connect the driver to the cluster via an instance of the MongoClient class. Create a python script, open it via a code editor and write the given code:

import pymongo
my_client = pymongo.MongoClient( < your connection string >)

7. Inserting Documents

The MongoDB database can have several collections. You can refer to an already existing collection with the code below:

my_collection = my_database.foods

Take note that the collection gets created only after you add a document to it. You can add a document to your collection with the insert_one() or insert_many() methods. Here are some code snippets to illustrate the same:

my_collection.insert_one({
    "_id": 1,
    "name": "pizza",
    "calories": 266,
    "fats": {
        "saturated": 4.5,
        "trans": 0.2
    },
    "protein": 11
})
my_collection.insert_many([
    {
        "_id": 2,
        "name": "hamburger",
        "calories": 295, "protein": 17,
        "fats": { "saturated": 5.0, "trans": 0.8 },
    },
    {
        "_id": 3,
        "name": "taco",
        "calories": 226, "protein": 9,
        "fats": { "saturated": 4.4, "trans": 0.5 },
   }
])

Once you have created a MongoDB document, you can run queries on it, update it, or even delete it as per need.

How to Create a Database in MongoDB Cloud?

The first step to using MongoDB is to have a database and a corresponding collection sorted out. Databases can store several collections, and the collection, in turn, will store all the documents. Furthermore, the documents store all the relevant field names and values.

There are a couple of different ways to create a MongoDB database. Here, we’ll discuss how to do the same via MongoDB shell or Compass, both of which are compatible with cloud databases like MongoDB Atlas and self-managed ones as well.

1. Via the Command Line Interface (CLI)

MongoDB can also be used by CLI, just like most other software systems. Let’s see how we can create a MongoDB database via CLI:

Step 1. For this, first, you need to have access to a MongoDB cluster shell; then, you’ll be able to see all the databases in the cluster via the ‘show’ command

>show dbs
>show dbs

Step 2. Now, take note that there isn’t a ‘create’ command in the MongoDB shell. To create a database, you need to enter the ‘use’ command. In case the database doesn’t exist, then it will get created. You can use the given command to create a new database:

use mynewdb
Use MynewDB

That will create the database, but it won’t be shown until you add some data. 

show dbs

Step 3: Use the following command to add a document to your database:

>db.<collection>.insert(<data>)

For example: >db.user.insert({name:“Diana”,age:20})
Code snippet

Note: You can view which database is in use currently via the db command. If you want to switch to a different database, type the “use” command followed by the database’s name.

2. Via GUI, MongoDB Compass

The GUI of MongoDB, Compass provides additional features such as data visualization, performance profiling, and offering CRUD access. Given below are the steps to open Compass on MongoDB:

Step 1. Firstly, the client should have TLS and should be on the Whitelist. Other than that, you need to have a user account and a password on the cluster to be used. 

Step 2. Then, install MongoDB Compass on your system (if it is not already installed)

Step 3. Click on the MongoDB Compass icon to start it.

Step 4. Go to the Databases tab in Compass and click on the ‘Create Database’ button.

Databases Tab

Step 5. A dialog box will open up. Now, enter the name of the database and that of its first collection. Now, click on Create Database.

Create database

Step 6. Next, you need to insert one or more documents into your newly created database.

Step 7. Click on the database’s name to check out the collection created, then click on the collection’s name to check out the Documents tab.

Documents tab

Step 8. Then, hit the ‘Add Data’ button to insert document(s) into the collection. The user can add JSON documents one by one or add multiple documents at a time by enclosing them in an array separated by commas in square brackets.

Step 9. Once done, click on “Insert.”

Conclusion

MongoDB is a popular and powerful distributed document database. Not only does it provide you with a lot of options, but it is also as powerful as SQL, if not more. We hope this blog cleared your doubts and provided you proper insight and guidance about MongoDB.

Frequently Asked Questions

Is MongoDB NoSQL?

MongoDB has been ranked as the most popular NoSQL database in the world. It is an open-source document-based database.

How to use MongoDB?

MongoDB is a fairly easy-to-learn system. It involves learning basic database things like querying via commands, filtering data, updating, etc. You can find all about it, including tutorials, here.

What type of database is MongoDB?

MongoDB is an open-source, cross-platform, and powerful distributed document database. It is a NoSQL database which means it doesn’t use tables. MongoDB removes the limitations faced with relational databases concerning large volumes of data.

What is MongoDB written in?

MongoDB was first written in C++. But, today, it is available in C++, Javascript, Python, and Go.

What is Mongoclient?

MongoClient is used to interact with the MongoDB database. Here is the code snippet you need to run to connect to the database/cluster database if you are using a Python driver:
import pymongo
my_client = pymongo.MongoClient( <pass your connection string>)

Recommended Articles