Getting Started with MongoDB Shell: Commands & Usage Simplified

• February 4th, 2022

MongoDB Shell cover

In a Relational Database system, the data is stored in rows and columns and is considered a Vertically Scalable Database. However, a large number of tables makes such Databases complex, and querying them becomes problematic. Consequently, it becomes difficult for the users to access and search through Relational Databases. Whereas, in a Non-relational Database like MongoDB, users can quickly access and search through Databases due to indexing. This article talks about the MongoDB shell and how you can use it to insert data into documents.

The data in MongoDB Databases are in the form of keys and values instead of rows and columns, which makes it flexible for users to add and remove documents in MongoDB Databases. Today, users can leverage MongoDB Databases through Graphical User Interface (GUI) or command-line interface. The MongoDB Shell offers a modern command-line experience. Let’s discuss how you can use the MongoDB shell and commands.

Table of Contents

Prerequisites

Understanding of types of Databases.

What is MongoDB?

MongoDB is an open-source, unstructured, NoSQL Database and an alternative to traditional Databases that store data in rows and columns. When applications require high unstructured data storage and data flexibility, MongoDB becomes the go-to Database for developers. It keeps the document in JSON format, i.e., Javascript Object Notation format, making it easy to access the data.

What is the Need for MongoDB?

MongoDB is a NoSQL Database that stores unstructured data in its JSON format. Unlike MySQL, which stores data in tables, MongoDB stores data in documents. Since it is a schema-less Database, MongoDB does not require any data structure to store information. Consequently, adding and deleting documents becomes easy in MongoDB.

Now, let’s dive straight into the MongoDB shell.

Simplify MongoDB ETL Using Hevo’s No-code Data Pipeline

Hevo Data is a No-code Data Pipeline that offers a fully managed solution to set up data integration from MongoDB and 100+ Data Sources (including 30+ Free Data Sources)and will let you directly load data to a Data Warehouse or the destination of your choice. It will automate your data flow in minutes without writing any line of code. Its fault-tolerant architecture makes sure that your data is secure and consistent. Hevo provides you with a truly efficient and fully automated solution to manage data in real-time and always have analysis-ready data.

Get started with hevo for free

Let’s look at some of the salient features of Hevo:

  • Fully Managed: It requires no management and maintenance as Hevo is a fully automated platform.
  • Data Transformation: It provides a simple interface to perfect, modify, and enrich the data you want to transfer.
  • Real-Time: Hevo offers real-time data migration. So, your data is always ready for analysis.
  • Schema Management: Hevo can automatically detect the schema of the incoming data and map it to the destination schema.
  • Scalable Infrastructure: Hevo has in-built integrations for 100’s of sources that can help you scale your data infrastructure as required.
  • Live Monitoring: Advanced monitoring gives you a one-stop view to watch all the activities that occur within Data Pipelines.
  • Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
Sign up here for a 14-day free trial!

Getting Started with MongoDB

To work with the MongoDB shell, you need to install MongoDB on your desktop. According to your operating system, you can visit the official MongoDB documentation to download the MongoDB setup.

Installation and Configuration of MongoDB Server

  • After downloading and installing the MongoDB Server, go to the Program Files and select the MongoDB directory. You get the following path.
C: -> Program Files -> MongoDB -> Server -> 4.0(version) -> bin
  • In the bin directory, there are two files that are:
    • mongod: Mongo Daemon (mongod) is used to manage all the server tasks of MongoDB like accepting requests, memory management, responding to clients, etc.
    • mongo: mongo is a command-line MongoDB shell that can interact with the client.
  • You need to create some directories to start the MongoDB Server. Go to the C-drive and open the command prompt.

Note: This tutorial uses the MongoDB Server on Windows. You can also install it depending on your Operating System.

  • Type the following command in the above-mentioned MongoDB shell command prompt.
C:> mkdir data/db C:> cd data C:> mkdir db
  • The above directory ‘db’ stores all the data of the MongoDB Server. The default directory path of the MongoDB directory will be data/db.
  • Go to the previously open bin folder and run the following command.
mongod

Note: The above MongoDB shell or the terminal is the mongo shell.

  • Go to the bin folder in C-drive and enter the below command.
mongo
  • Go to the mongo shell, where you can see a connection accepted message. It ensures that the installation and configuration are successful.
  • Run the below command in the MongoDB shell (mongo). It shows the current Database that you are in.
db
  • To set up the environment variables for Windows, you can use the following menus.
Advanced System Settings -> Environment Variables -> Path(Under System Variables) -> Edit
  • Copy the path of the bin folder and paste it into the above system variables path. Thus, the environment variables are set.
  • The following command will show the list of Databases.
show databases;
MongoDB Shell
Image credit: Freecodecamp
  • From above, there are 4 Databases created: CrudDB, admin, config, and local.
  • To use the specific Database, you can use the below command.
use <your_db_name>
  • Example: Use student;

Insertion in MongoDB

After creating the Database, you need to insert some data. Since data in MongoDB is unstructured, it is stored in collections.

There are two types of collections in MongoDB.

  • Capped Collection: It is used to declare the fixed size of the collection.
    Example: db.createCollection(“mySecondCollection”, {capped : true, size : 2, max : 2})
    The above command true is used to enable capping in MongoDB, and size specifies the size in megabytes. And max tells the maximum number of documents.
  • Non-capped Collection: It does not declare any fixed size to insert the collection.
    Example: db.myCollection.insert({“name”: “john”, “age” : 22, “location”: “colombo”})
    The above command creates the collection called myCollection, and it inserts a document with name and age.

There are three ways to insert data in collections. They are:

  • insertOne(): As the name suggests, it is used to insert data in one document. 
    Example:
MongoDB Shell: insertOne
Code credit: Freecodecamp
  • insertMany(): It is used to insert data in more than one document.
    Example:
MongoDB Shell: insertMany
Code credit: Freecodecamp
  • insert(): It is used to insert data in as many documents as users want. insert() works the same as insertMany().

In MongoDB, whenever you insert some data, it automatically adds an id to the data in the document. E.g., to find all the data from the Database, use the below command.

db.myCollection.find()

The output is:

MongoDB Shell: find
Image credit: Freecodecamp

If you want to see the output in JSON format, use the following command.

db.myCollection.find().pretty()

It shows the following output.

MongoDB Shell: pretty()
Image credit: Freecodecamp

Therefore, you can see an id associated with every data from the above output. If you want to remove this id, you can use the below command.

db.myCollection.find({}, _id: 0).pretty()

Filtering Data in MongoDB

In MongoDB, if you want to display the specified document by using a single detail, you can do that by filtering data.

Example 1:

MongoDB Shell: myCollection.find
Code credit: Freecodecamp

The above queries consist of only the name in the document; you can display the entire document through the below output using the name.

MongoDB Shell: Code Example
Image credit: Freecodecamp

Example 2:

Suppose you want to display documents of people whose age is less than 25, you can use the $lt filter.

  • $lt is for less than.
  • $gt is for greater than.
  • $lte is for less than or equal to.
  • $gte is for greater than or equal to.
  • $ne is for not equal.

Updating the Document in MongoDB

db.myCollection.update({age : 20}, {$set: {age: 23}})

There is a simple query to update data in the document from above. The first field is age: 20, which determines the data to be updated, and the following field is the actual data. But, here, the specific data in the document is not specified. Therefore, it changes all ages in the document to 23.

Suppose you want to update the data in a document named ‘navindu’ and add one more property to it as a location, you can do it with the below queries.

db.myCollection.update({name : navindu}, {location: “mokola”})

You will get the below output.

MongoDB Shell: Code Example 2
Image credit: Freecodecamp

If you want to remove the property from the document, you can use the below query. It will remove the property named age.

db.myCollection.update({name: "navindu"}, {$unset: age});

Deleting the Document in MongoDB

To delete data in MongoDB Databases, you can use the following command.

db.mycol.remove({'title':'MongoDB Overview'})

The above command consists of “mycol” collection and removes the document with the title ‘MongoDB overview.’ If the document is not specified in the query, it will remove all the documents in that collection.

Indexing in MongoDB

Indexes in any Database are used as a data structure to store the data. Similarly, in MongoDB, indexes are used to store some fields of the document. If there are no indexes in MongoDB, searching documents becomes difficult; indexing can search the number of indexes instead of the entire document.

You can create an index in MongoDB using the below command.

db.studentdata.createIndex({student_name: 1})

It shows the following output.

MongoDB Shell: Code Example 3
Code credit: Beginnersbook

From the above output, the studant_name is the collection’s name in MongoDB. The ‘1’ is the key that decides the order of the indexes, and it can be ascending or descending. The descending order is given by ‘-1.’

If you want to find all the indexes in the collection, you can use the below command.

db.studentdata.getIndexes()

The above command shows all indexes of the “studentdata” collection.

To drop an index, you can use the below command.

db.studentdata.dropIndex({student_name: 1})

You can also drop all the indexes in a collection through the following command.

db.studentdata.dropIndexes()

Graphical User Interface(GUI ) for MongoDB

From the above steps, you have learned about MongoDB collection, insertion, and deletion of records with a command-line interface. However, if you want to build an extensive system with a high volume of data and complex queries, you should use GUI. As a result, MongoDB provides the user with an additional GUI tool called Compass.

Follow the below steps to use GUI with MongoDB Server.

  • You can download the MongoDB Compass from the MongoDB Compass site.
  • After installing the MongoDB Compass, you can see the below screen.
MongoDB Shell: Connect to Host
Image credit: Geekflare
  • To log in to the MongoDB Compass, you need to run the MongoDB Server and connect it with the default details.
MongoDB Shell: Collections
Image credit: Geekflare
  • You can see the list of available collections in the Database from above. The tutorial is the name given to the Database. If you click on any collection, it displays the list of documents. They can be in the tabular form or JSON form.
MongoDB Shell: Documents
Image credit: Geekflare
  • It is straightforward to add a document in GUI. You have to click on the insert document as shown above. It opens the dialog box that has the document’s details and the id. Therefore, creating the collection and adding or removing documents in GUI is very simple compared to the command-line interface.

Conclusion

In this tutorial, you have learned about the MongoDB Server, its configuration and installation, and inserting data in documents using the MongoDB shell. The MongoDB GUI that is Mongo Campus is also being discussed here. You can also execute other features like Mapreduce and Replication in MongoDB.

visit our website to explore hevo

Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources like MongoDB and a wide variety of Desired Destinations, with a few clicks. Hevo Data with its strong integration with 100+ Sources & BI tools (including 40+ free sources) allows you to not only export data from your desired data sources & load it to the destination of your choice, but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.

Want to take Hevo for a spin? sign up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable plans & pricing that will help you choose the right plan for your business needs.

Share with us your experience of working with MongoDB shell in the comments below!

No-code Data Pipeline For Your Data Warehouse