How to Manage Data in MongoDB

So, how do we manage data in the database? Two words. Through queries. A query requests information (or data) from a database. Queries can be used to perform some sort of CRUD (create, read, update, delete) function to data stores in a database. Queries in MongoDB use the MongoDB Query Language (MQL). The language is easy to learn and has a wide range of options, operators, expressions and filters to manage data. We will be performing queries using MongoDB Shell.  MongoDB Shell (also referred to as mongosh) is MongoDB’s interactive JavaScript interface. It allows you to add, modify and delete data from the document database. In the previous article, we created a database called ‘myDB’ with a collection named ‘collection01.’ As of now, the database we created in the previous article is empty. So how will we connect with the database to start adding data? Fortunately for us, we created our database in MongoDB Atlas. MongoDB Atlas is a hosted MongoDB service option, so we do not have to worry about installing additional overhead. We can simply connect to the database and perform queries through any available connection methods. First, we will need to download and install the MongoDB shell. We will use the shell to manage data in the cluster. Navigate to the cluster and click the “Connect” button. For the connection method, choose “Connect with the MongoDB Shell.”

Follow the instructions and download and install the shell. When you run mongosh (Mongo Shell), you will be prompted for a connection string. Run your connection string in your command line when prompted. Once you have successfully installed mongosh, you can open a terminal and start using the shell. To get a list of commands and syntax use ‘mongosh –help.’

Open the terminal and type ‘mongosh’ to start the MongoDB shell.

Now that we have successfully installed the shell and have it up and running, we have everything we need to run queries on the database. We will need a way to update data in your database to reflect changes made on the front end by the user or another application. That is where CRUD comes in. CRUD defines the basic functionality that we need to perform on our data. For example, if a user creates a new comment on a blog post, that comment must also be updated in the database. That way, when other users visit the blog post, they can see every comment previously posted.  Let’s say we wanted to store data for a note-taking app. First, we decide and plan features and functionality. Then, we must consider what fields and actions we must perform to support the features and functions we defined. For this example, we want to store data for a note-taking app with the following data points in a document:

Performing queries in MongoDB

Create

To add the data points, we first switch to the myDB database using ‘use myDB.’ MongoDB will create the database if you do not already have it. Then we can start using queries to create and manage collections of documents. In the example below, using the insertOne() method, we create a new document to hold the note “this is my first note” in a newly defined collection called notes. For example, we use db.notes.insertOne({note:’this is my first note’}) to create a new note:

As you can see, the response shows the database accepted the request and automatically generated a unique id value for the document. Let’s add a couple more notes using the insertMany() function. This function allows us to insert multiple documents at once. 

We can use the find method to list all documents in the notes database using the find method db.notes.find():

Read

The read function of CRUD allows you to view records (or, in our case, documents) in a database based on some search criteria. Running the find command shows that we have a level of read access already. Below is an example of other data on our database we can read. We can view (or read) a list of databases using show dbs, get a list of collections in the database db.getCollectionNames().

Update

Once we have our data stored, perhaps one of the most necessary functions is to be able to update an existing record. The db.collection.updateOne() and db.collection.updateMany() functions can be used to update one or many documents in a collection, respectively. Let’s update our existing note. Using the document’s unique id, we will add additional data points.

In the example below, we use the db.collection.updateOne() function to update the document we just created. We will add a date field, an array of keywords and a boolean that indicates whether or not the note was reviewed. In the example below, we use the updateOne() method to find the document by the note value and add an array of keywords: db.notes.updateOne({note: ’this is my first note’},{$set: {keywords: [‘MongoDb’,‘Infosec Institute’, ‘database’, ’learning’]} })

The database acknowledges the query and reports the document as modified. Run the find() function to view the updated document. Best practices encourage us to refer to documents by their unique id as indicated by the _id whenever possible. In the example below, we use the document’s id to add a date and Boolean to support the data we need to store.

The note is now updated to include a ‘date’ field that holds the current date and a ‘reviewed’ field that holds a Boolean value.

Delete

Lastly is the delete functionality of CRUD. As implied, you use to delete to remove existing database entries. In MongoDB, you can delete users, databases, documents and so on. The db.collection.deleteOne() and db.collection.deleteMany() functions can be used to delete one or many documents in a collection, respectively. In the example below, we use db.collection.deleteMany() to delete the entries that do not have a date field. This will remove the last two entries we created.

Play with the example and make as many updates as you would like. Our data stores just a few of the data types supported by MongoDB. There are also many more commands available in MongoDb’s official documentation. Being able to distinguish correctly written queries is very useful in debugging errors. 

Connecting a MongoDB database

We learned how to connect to a MongoDB database! We also briefly ran some commands to query and manage data for our new application. Data management is handled using queries. Queries perform CRUD (create, read, update or delete) functionality. Visit the official documentation for more commands used to manage data via the MongoDB Shell.  In the next article, we will look at how to secure data in MongoDB. Check out my Infosec Advanced Splunk Core courses to learn more. 

Sources

What is a Document Database?, MongoDB