How to Get started with MongoDB

Learn what MongoDB, installation guide and basic operation are.

In object-oriented development, we’re encouraged to approach code development through logical models, so that we can more readily conceptualize it in our mind. When we do this, we’re better able discern the logical operations used to interact with it and information that it would contain at different times.

What if you could store the programmatic models almost exactly like you model them? What if you could store them as they are instead of in a series of rows in tables? By learning about MongoDB, you’re going to be able to do just that!

MongoDB NoSQL is trending more than ever. Do you have a necessary understanding of it? Don’t worry if not, the following will help you.

Introduction

With the website taking a paradigm shift towards dynamic content, the demand for No-SQL database rose.  This gave rise to numerous No-SQL databases like MongoDB.

Classified as a No-SQL database, MongoDB is a document based database which stores the data in the form of JSON documents with an autogenerated identified for every document.

A No-SQL database is a database where the table structure is not fixed, unlike structured SQL databases. MongoDB stores the data in the form of JSON string irrespective of the count of attributes or name of attributes in a specific column.

This allows the developers to rapidly make changes in the entities without the need for any changes in the database level.

Installing MongoDB

MongoDB, just like every other database, is available in multiple variants depending on the development needs. The variants have been listed below and can be used or download from this link

  • MongoDB Atlas – Database as a service
  • Community Server – Free to use for the community of developers
  • MongoDB Enterprise Edition – The commercial version with additional features

Each of these is fully compatible with every operating system. To begin with, the installation of community server, download the relevant installation file as per your operating system.

The installation process slightly differs for every operating system, and hence we would go through each operating system installation separately.

Installing in MacOS

To install MongoDB in MacOS. Download the .tgz archive containing the necessary binaries in it. On unarchiving the file, you should be able to view a bunch of binaries located in the bin folder.

  • Move the bin folder to the desired location
  • Open a terminal and change the directory to the bin directory mentioned above
  • Execute the below command to create a database at the desired location.
$ ./mongod --dbpath /path-to-desired-directory/

In the above command, replace the path to the directory with your desired path and the server will be started as soon as the command is executed.

Installing in Windows

MongoDB download center provides an executable .msi package for installing MongoDB into windows. The installation in windows is quite straightforward and can be done using a few commands once the setup has been downloaded.

  • Execute the below commands to install MongoDB in Windows PC/server.
> cd /setup-folder/
> msiexec.exe /q /i .msi ^
INSTALLLOCATION="C:\Program Files\MongoDB\" ^
ADDLOCAL="MonitoringTools,ImportExportTools,MiscellaneousTools"

The above commands will take you to the corresponding directory and execute the setup for installation at the specified location. Once installed, you need to configure the default database storage path for MongoDB. The below command helps you configure the same

> md \db\data

The above command creates a db/data folder in the directory where the command prompt is pointing to currently. In case you need to reconfigure the database again, you could use the mongod.exe with the dbpath argument as shown below:

>"C:\Program Files\MongoDB\bin\mongod.exe" --dbpath d:\tutorial\mongodb\data

Installing in Linux

Similar to the MacOS downloads, MongoDB for Linux variants is also available in the form of an archived bunch of binaries. The process to install MongoDB is quite similar.

  • Move the binaries to the desired location
  • Open the terminal in the folder
  • Execute the below command with the desired DB location
$ ./mongod --dbpath /path-to-desired-directory/

Creating the first collection

MongoDB stores the data in the form of JSON documents. A group of such documentation is collectively known as a collection in MongoDB. Thus, a collection is analogous to a table in a relational database while a document is analogous to a record.

To store documents, we first need to create a collection. The exciting thing about a NoSQL database is that unlike SQL database, you need not specify the column names or data types in it.

The first step towards creating a collection is to create a database. To create a database and connect to it using the command line, execute the below command from the MongoDB installation home directory.

$ ./bin/mongo tutorial

This command is used to start the database connection and connect to the tutorial database simultaneously. It will show a bunch of lines in the log to indicate that the command line has connected to the MongoDB database.

A sample command line image has been displayed below to give you a better idea about the same.

  • To create a collection, execute the below command:
 
$ > db.createCollection('firstCollection');

This is how an empty collection is created. The next step is to insert data and do some processing on the records using the MongoDB command line.

Inserting a document into the Collection

As discussed above, it is possible to insert almost any JSON into every MongoDB collection.

Let us start with insertion of the first JSON document into the firstCollection collection created above.

> db.firstCollection.insertOne({name:'Sophia',skill:'MongoDB'});

The above command inserts a single JSON document into the firstCollection. The same could be verified by using the command shown below:

> db.firstCollection.find();

The above command has got multiple uses depending on the variation of the find() function. When there are no arguments specified as is the case with the above command, it fetches all the available documents from the collection.

You could insert one more records and try the same. On doing so, the output of the above command would be similar to the one shown below:

> db.firstCollection.find();
{ "_id" : ObjectId("5b043a32c29a7184535e783a"), "name" : "Sophia", "skill" : "MongoDB" }
{ "_id" : ObjectId("5b05b4f0c29a7184535e783b"), "name" : "DataMounts", "skill" : "Java,MongoDB,NodeJS" }

As it can be seen, there are two available records being shown. The find() function could be easily used to filter the documents based on specific parameters. Let us filter the document using name attribute.

The filter process is simple, and it could be understood from the command below:

db.firstCollection.find({name:'Sophia'});
{ "_id" : ObjectId("5b043a32c29a7184535e783a"), "name" : "Sophia", "skill" : "MongoDB" }

The filter can also be used with multiple attributes in the JSON. Although it is possible to add any number of parameters to the query, the limitation of this approach is that it matches only the exact value of attributes.

Filtering records using Regex

To execute a MongoDB equivalent of a MySQL like clause, MongoDB uses regex. Regex is a series of characters forming a pattern to match. The regex literals are similar to the ones used in Javascript.

For the current collection, we will try to fetch the data by matching a pattern for the skill attribute. The below command gets the list of people with the skill MongoDB. Thus, it will fetch two records as both contain the string MongoDB.

> db.firstCollection.find({skill:/.*MongoDB.*/});
{ "_id" : ObjectId("5b043a32c29a7184535e783a"), "name" : "Sophia", "skill" : "MongoDB" }
{ "_id" : ObjectId("5b05b4f0c29a7184535e783b"), "name" : "DataMounts", "skill" : "Java,MongoDB,NodeJS" }
> db.firstCollection.find({skill:/.*Java.*/});
{ "_id" : ObjectId("5b05b4f0c29a7184535e783b"), "name" : "DataMounts", "skill" : "Java,MongoDB,NodeJS" }

The above code displays the result of two different strings in the regex form. The first query fetches the list of a document where the skill attribute contains the keyword MongoDB while the other one fetches people skilled in Java only.

The next challenge in querying based on criteria is to query with an OR or AND condition.

Complex queries in MongoDB

As it is clear from the above commands, MongoDB where clauses work on JSON. The process of combining conditions is also dependent on JSON itself. MongoDB provides operators like $or, $and as well as $not to do the relevant query operations.

Let us try to get the list of documents where name attribute contains Sophia or skill contains Java.

> db.firstCollection.find({$or: [{name:'Sophia'},{skill:/.*Java.*/}]});
{ "_id" : ObjectId("5b043a32c29a7184535e783a"), "name" : "Sophia", "skill" : "MongoDB" }
{ "_id" : ObjectId("5b05b4f0c29a7184535e783b"), "name" : "DataMounts", "skill" : "Java,MongoDB,NodeJS" }

As it can be seen, it fetches both the records. You could try to use the name attribute as DataMounts and see the change. Only the document with three skills and name DataMounts will be displayed.

Similarly, it is possible to use $and operator with a JSON array of conditions as shown above.

For the next set of operators, we would need to create one more collection and add some records to it using the commands below.

> db.createCollection('studentmarks');
{ "ok" : 1 }
> db.studentmarks.insertMany([{name:'A',marks:20},{name:'B',marks:25},{name:'C',marks:22},{name:'D',marks:30}]);
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("5b06e7b5c29a7184535e783c"),
		ObjectId("5b06e7b5c29a7184535e783d"),
		ObjectId("5b06e7b5c29a7184535e783e"),
		ObjectId("5b06e7b5c29a7184535e783f")
	]
}

The next set of operators that we would use are comparison operators in the query. To compare values using criteria like less than or greater than or not equal to, we use the relevant operators in the value that we pass.

An example of getting a list of students with marks greater than 22 is shown below.

db.studentmarks.find({marks:{$gt:22}});
{ "_id" : ObjectId("5b06e7b5c29a7184535e783d"), "name" : "B", "marks" : 25 }
{ "_id" : ObjectId("5b06e7b5c29a7184535e783f"), "name" : "D", "marks" : 30 }

The $gt here indicates greater than in the criteria. Thus, the documents with marks more than 22 is being displayed. Similarly, there are other operators that can be used. They are listed below.

OperatorUseExample
$eqCheck if the value is equal{marks:{$eq:20}}
$ltCheck if value is less than{marks: {$lt:20}}
$gteCheck if value is greater than or equal to{marks:{$gte:22}}
$lteCheck if value is less thank or equal to{marks:{$lte:22}}
$neCheck if value is not equal to{marks:{$ne:22}}
$inCheck if value is equal to either of the values from the array{marks:{$in:[20,22]}}
$ninCheck if value is not equal to any value from the array{marks:{$nin:[22,25]}}

GUI for MongoDB

In the discussion above, we have used a command line to execute our queries in MongoDB.

Using command line could be challenging when it comes to complex queries and a larger bunch of data. To make it easier to view the data and execute the queries, MongoDB provides you with an excellent GUI tool called the MongoDB Compass.

MongoDB compass can be easily downloaded from the MongoDB downloads site. Once you have downloaded and installed MongoDB Compass, start the application, and you would be welcomed by a screen similar to the screen shown below.

MongoDB - Connect to Host

Considering that you have the MongoDB server up and running, click connect with the default details. You should be logged in and shown the list of available databases.

Click the tutorial database to check out the list of collections in the tutorial db. As shown below, it displays the list of available collections in the tutorial db.

MongoDB - Collection

On clicking the collection, it displays the list of documents with the necessary controls to filter the records using a JSON as well as the facility to view the documents in a JSON format or tabular format as per our convenience.

The GUI also makes adding a document simpler. All you need to do is click the Insert Document button in the screen shown below. It opens up a small dialog asking for the document details with an auto-generated document id.

MongoDB - tutorial

GUI simplifies a lot of operations that might be difficult to perform using MongoDB command line interface.

Conclusion

We captured the essence of NoSQL with a variety of examples and understood installation, how documents are different compared to a typical relational database record.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time
Comments

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More