MongoDB Beginners Tutorial

In the last decade, the NoSQL approach for developing databases has increased dramatically. NoSQL database refers to the databases without fixed schemas. Unlike relational databases, NoSQL databases are not table-based.

Although NoSQL databases have lower transaction safety, they are fast in accessing data. Moreover, scalability is also better than relational databases. MongoDB, Cassandra, Redis, HBase, Neo4j, Oracle, NoSQL, and Couchbase are few popular NoSQL databases.

MongoDB

MongoDB is one of the most popular NoSQL databases today. It is a core part of MEAN and MERN stacks that are used for web application development. MongoDB stores data in key-value pairs represented as JSON structure in objects.

These objects are known as documents. These documents, are in, turn stored in dynamic collections. And collections are stored in a MongoDB database. We will discuss more about MongoDB documents and collections, but first, we will go through installation steps.

Installing MongoDB on Windows

To install MongoDB in windows, open a browser and go to the following link.

https://www.mongodb.com/download-center/community?jmp=docs.

Select the latest version of MongoDB and your Windows OS. You will have two package options. Select the MSI option. Then, click the download button. It will download a .msi package. Open it after the download is complete and go through the installation steps.

By default, MongoDB will be installed in the C drive. Open the C:/Program Files folder/MongoDB/Server folder. Open it. In this folder, you will find yet another folder. In my case, the name of the folder is “4.2”. Folder name depends upon the version you have downloaded. Open this folder and you will find a few other folders and files. Open the folder named “bin”. The file we need to start MongoDB is present in this folder. The name of this file is “mongod”.

Open a terminal and go to the path where mongod file resides and then type “mongod”.

And it won’t work. Check the exception that it throws in the above image. It says we need a directory for storage in this path “C:datadb”. So, create this path with proper permission(Read and Write) and then again run the “mongod” command. Now the server will start listening on port 27017.

Documents in MongoDB

MongoDB documents are composed of key-value pairs in JSON format. But the documents store data in BSON, the binary representation of JSON. Documents in MongoDB are similar to rows in SQL.

This is how a MongoDB document looks like.

{
	name : "Tommy",
	age: 21
}

The name and age are keys. “Tommy” and 21 are their values, respectively. There can be any number of key-value pairs in a MongoDB document. Because BSON, there is a vast range of data types that can be stored in a document. The following are the data types that are supported by BSON.

  • Double
  • String
  • Object
  • Array
  • Binary Data
  • Undefined
  • ObjectId
  • Boolean
  • Date
  • Null
  • Regular Expression
  • DBPointer
  • JavaScript
  • Symbol
  • JavaScript with scope
  • 32 bit Integer
  • Decimal 128
  • Min key
  • Max key

Many of these data types are not present in JSON.

Documents, in turn, are stored in collections. Each document in a collection doesn’t need to have the same fields or the same number of fields. Observe the following example.

{
	name : "Tommy",
	age: 21	
},
{
	name: "Johnny"	
},
{
	name: "Mark",
	age: 21,
	on-site: true	
}

 

There are three documents, and each of them has a different number of fields. This works perfectly with MongoDB unless you have applied any validations, though. And moreover, we can also store documents in documents.

{
	name : "Tommy",
	age: 21,
	address : {
		street: "third",
		housenumber: 21,
		city: "New York"
	}
}

So documents in MongoDB can have any number of key-value pairs. There are various data types because of BSON, and we can also have embedded documents.

Collections and Databases

Documents in MongoDB are stored in collections. Collections in MongoDB are similar to tables in SQL. There can be any number of documents in a single collection. Collections, in turn, are stored in a database. Similar to tables in SQL that are also stored in a database. As there can be any number of tables in a single database, there can be any number of collections in a database.

So let’s discuss how to create all these in MongoDB.

 

First of all, we need to start the mongo shell. Remember, earlier, we used the mongod command to run MongoDB? Open a terminal and start the terminal again. After that, open another terminal and go to the same path – “C:Program FilesMongoDBServer4.2bin”. This is the path in my machine. “4.2” can vary depending upon the version of MongoDB installed in your device.

Type “mongo” and press enter. It will start the mongo shell. But do not close the terminal where MongoDB is running.

mongo is the command-line shell that connects to a specific instance of mongod. When you run mongo with no parameters, it defaults to connecting to the localhost on port 27017.

Type command “show dbs” to view all the databases.

These are the default databases. Let’s create a new database. It’s very simple. Just type “use” followed by the name of the database.

If there doesn’t exist a database with the name specified, MongoDB will create a new one. If it already exists, it will switch to that database.

Type command “show collections” to view all the collections in this database.

Currently, there is no document in the database. There are two ways of creating a collection.

db.createCollection()

The db.createCollection() method creates a collection explicitly. It has two parameters – the name of the collection and various options. There are various options, such as capped, size, max, validator, and many more. These options are optional.

So let’s create a collection using this method.

db.createCollection("employees")

It returns an object. The value of “ok” is 1, it means collection was created successfully. Let’s try “show collections” command once again.

There is one collection in the database. Before moving to the next way of creating a collection, I will demonstrate how to insert documents in a collection. It will be easy to understand the second way if you know how to insert documents in a collection.

Inserting documents

We can insert documents in a collection one-by-one using the insert() method, or we can use the insertMany() method to insert multiple documents. For the time being, we will insert a single document using the insert() method.

 

db.employees.insert({name: "TOMMY", age: 21})
One document is inserted into the employee’s collection. Here we passed a single object to the insert() method. In the insertMany() method, we have to pass an array of objects.

To view the documents in the collection, we can use the find() method. pretty() method is used to just display the data in pretty format.

db.employees.find()
db.employees.find().pretty()

The find() method returns all the documents present in a collection. Attaching pretty() with the find() method will display the documents in a better way.

Another way of creating a collection

Now, we will discuss the second way of creating a collection.

Currently, there is only one collection in the newdb database. Instead of using the db.createCollection() to create a collection first and then using the insert() or insertMany() method, we can directly use these methods and skip the db.createCollection() part.

 

db.employeespart2.insert({name: "Jonny", age: 24})

Observe the above command carefully. Here, one document is inserted into a collection using the insert() method. But the name of the collection is not “employee”, it’s “employeepart2”. But we never created any collection of this name, right? Using the insert() or insertMany() method, this will automatically create the collection if it does not exist. Let’s verify.

So these are the two ways of creating a collection.

Wrapping Up

So we discuss a lot about MongoDB basics. It is one of the most popular NoSQL databases. MongoDB is a lot simpler than SQL. We discussed a few queries for inserting and retrieving data, and I bet you can find them very simple and easy to use when compared to SQL queries. There are many more in MongoDB, but these basics about documents and collections are necessary to understand before you can move further.

Leave a Comment