MongoDB, The Complete Guide [Part 3]

Go over Part 1 & 2 before jumping into this part so that the understanding would be much more interactive. In this lesson, I will introduce all of the basic Mongo Shell command operations that can be performed (e.g., creating, reading, updating and deleting from a database).

CRUD operations from the shell

Once the MongoDB server is up and running, one can connect to it using Mongo shell client. Here are the official docs for all the installation.

All the functionalities that are provided in the shell client are provided through MongoDB drivers too. Drivers are provided for all popular programming languages, which means that all features that are shown in this chapter can (and should) be done through the code. However, for demonstrative purposes, the shell client is used.

It’s important to note that MongoDB commands are case-sensitive.

Using mongo

To start the shell client, type the following command in the terminal :

mongo

You’ll see that the client displays some basic information, such as client and server versions. Finally, the shell client brings the user to a prompt, where commands may be typed.

Creating a Database

At the top of the hierarchy, in the MongoDB server, is database entity. There can be multiple databases on a single server.

To create a database, MongoDB provides the command:

use DATABASE_NAME

This command:

  • is used when a user wants to switch from one database to another.
  • will create a new database if it doesn’t exist; otherwise, it will select the existing database.

If one needs to check on which database the client is connected to, db the command will display that information.

db

Example

So, let’s create our first database by typing this command in the terminal:

>use blog

Using db.help()

Once the database is created and connected to, a user can manipulate the data inside of that database. This is done by using one of the many options of the db entity.

All the options will be displayed by typing in the

db.help()
Image for post
Image for post
[Running db.help() command]

Collection Operations :

Creating a Collection

Now, the first thing a user would need to do is create a collection.

This is achieved by using the method.

> db.createCollection(COLLECTION_NAME, OPTIONS)

Showing Collections

The list of existing collections can also be displayed using the command.

> show collections

Dropping Collections

Existing collections can be removed with the method.

> db.COLLECTION_NAME.drop()

Example

So, let’s drop one collection, and use show collections to verify the result.

Image for post
Image for post
[Dropping the collection “user”]

Once a collection is created, a user can insert, read, update and remove documents from it.

Inserting a Document

For adding a document to the collection

db.COLLECTION_NAME.insert(JSON_DATA)

the method is provided.

Alternatively, the

db.COLLECTION_NAME.save(JSON_DATA)

function can be used.

Example

This feature is displayed below:

db.user.insert({“name” : “Sarthak”, “blog” : “beautifulmonkey.net”, “numberofArticles” : 10, “company” : “MadarCode”});

Querying Documents

For a user to query documents from the database, the following functions are provided:

db.COLLECTION_NAME.find(QUERY)

and

db.COLLECTION_NAME.findOne(QUERY)

Data can also be presented in a formatted manner by appending the following method:

pretty()

A query that is passed into the function is a JSON object too.

Example

MongoDB has an additional query language that gives a user the ability to do something similar to the where clause.

For example, if we wanted to read all the users that have the blog name — beautifulmonkey.net, we could do something like this on the terminal:

db.user.findOne({“blog” : “beautifulmonkey.net”});

db.user.find({“blog” : “beautifulmonkey.net”});

db.user.find({“blog” : “beautifulmonkey.net”}).pretty();

Updating a Document

Every document in the database can be updated. This is achieved by using

db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Example

Let’s increase the number of articles for our document.

Type out the following command in the terminal:

db.users.update({“blog” : “beautifulmonkey.net”}, {$set : {“numberOfArticles” : 11}});
db.users.find({“blog” : “beautifulmonkey.net”}).pretty();

The additional $set filter was used, which helped us specify exactly which fields, inside of the document, should be updated.

Removing a Document

If a user wants to remove a document from the collection, one can do it with the

db.collection_name.remove(query)

method, as shown in the example below.

Example

Type out the following commands to implement this operation in the terminal:

db.user.find().pretty();

db.user.remove({“blog” : “beautifulmonkey.net”});

db.user.find().pretty();

Indexes

To achieve better performance, MongoDB provided indexes. They are not different from the traditional indexes of relational databases; however, without them, MongoDB must scan every document from a collection to select those documents that match the query statement.

This scan is highly inefficient because of the large volume of data.

Indexes are data structures which store a small portion of the data that is easily accessible through MongoDB.

Creating an Index

In order to create an index on the field of a collection, one should run:

db.COLLECTION_NAME.createIndex({ FIELD_NAME: 1})

Example

Let’s look at an example of how it’s done!

Type out the following commands in the terminal below:

db.user.createIndex({“blog” : 1});

Final Thoughts:

Try out all of the commands mentioned above in the terminal.

There are many other functionalities of the MongoDB language that we haven’t covered here, but these should be enough for the beginning. For more details on the MongoDB API itself, you can check out this page.

Look at the Appendix chapter to see how to install and run mongo on your local machine.

In the next part , we will take a look at the High Availability and High-Throughput Configurations.

That’s it for this part and congrats you made it so far. If you have any thoughts then let’s talk in the comments section or you can say hi at sarthak.acoustic@gmail.com.

Software Engineer @Vedantu, Former Intern @Hackerrank, GSoC @Wikimedia, Former Intern @Vedantu, Codeforces(Expert)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store