An Introduction to MongoDB

0
3230

MongoDB is an Open Source NoSQL type of document database. It is a cross-platform database that provides high levels of performance, scalability and can be used in enterprise applications that deal with large sets of data.

MongoDB was created in 2007 and is built on a horizontal scale-out architecture that stores data in a document style described in the JSON language. It can be used on platforms such as Windows and Linux, among others.

Reasons to use MongoDB

MongoDB can handle huge sets of data, is easy and quick to access, and can be used in a variety of applications and settings. It is used in the Internet of Things (IoT), banking and finance, gaming, e-commerce, logistics and content management.

  • It is fast and powerful, and convenient for moving data because of its document data model.
  • It supports a large set of both data and traffic because of its horizontal, scale-out architecture.
  • It offers a great user experience for developers.
  • It is accessible to anyone from anywhere — via the cloud through MongoDB Atlas, and free through the community edition.
  • It supports rapid iterative development.
  • It has great community support.

Problems that MongoDB solves

The problems that MongoDB solves are related to data management and software development.

  1. It enables the integration of large amounts of data from different sources into a unified single view, something other databases are unable to do.
  2. It is able to describe and support different types of complex data structures, even when they are constantly evolving. Geospatial data is also supported.
  3. Unlike other databases, MongoDB is highly scalable, enabling it to support applications that need high and efficient performance.
  4. Because of its flexibility in deployment, it is able to support hybrid and cloud applications, both private and public.
  5. On account of its document databases that are easier to use and understand, it supports agile development and collaboration in projects.

Features of MongoDB

Most NoSQL databases have certain default features common to all of them, but MongoDB has some additional useful features.

  • MongoDB is a high-performance efficient database. This is because it supports embedded data models and its query operations are faster.
  • It supports almost all CRUD operations and has a rich query language.
  • Its auto-replication feature provides a good back-up mechanism if a server fails.
  • It has the sharding feature that is responsible for horizontal scalability.
  • It supports multiple storage engines.

Application areas

MongoDB is mainly used in Web applications as the preferred database. It is used by the MEAN stack (a popular Web development stack) as the main database. MEAN is a combination of MongoDB, AngularJS, ExpressJS and NodeJS.

Demerits of MongoDB

1. Being a NoSQL database, it does not follow the principles of ACID (atomicity, consistency, isolation and durability). Therefore, it cannot be used in applications that need transactions at the database level or where ACID compliance is necessary.
2. It does not allow the use of stored procedures.

Trying out MongoDB

We will not be discussing how to install MongoDB in this article. So, let us start with creating a database and tables, and look at a few common use cases.

Type the following command to start MongoDB:

net start MongoDB

To run the MongoDB shell, type:

mongo

Type the command below to create a database:

use database_name

…where database_name represents the name of your intended database; e.g.:

use firstdatabase

Creating a collection

There are two methods of creating a collection.

1. Creating a collection when creating a document

You can insert a document in a non-existent collection, and MongoDB will automatically create the collection.

The syntax is as follows:

db.collection_name.insert({key:value, key:value…})

Example:

> use firstdatabasedb
switched to db firstdatabasedb

db.firstdatabase.insert({
name: “Charles”,
age: 27,
website: “firstdatabase.com”
})

The above will create a collection name, firstdatabase, and then insert the specified values. To check if the document was successfully inserted, run the following command:

db.collection_name.find()

To check for collection, run the following command:

show collections

2. Creating a collection before the documents

Here, you create the collection first and then you can insert documents into it. The syntax for this is shown below:

db.createCollection(name, options)

name represents the collection, whereas options is used to specify parameters.
Example:

> db.createCollection(“employees”)
{ “ok” : 1 }

Basic data manipulation methods are:

  • Insert document
  • Use of insert()

The syntax for this is:

db.collection_name.insert()

As an example, we insert a document in a collection named first collection:

db.firstcollection.insert(
{
name: “Charles”,
age: 27,
email: “admin@firstcollection.com”,
course: [ { name: “Databases”, duration: 7 }, { name: “Datastructures”, duration: 30 } ]
}
)

The insert() method is multifunctional as it can create a collection even if it does not exist. The course parameter above has several values inserted.

Inserting several documents in a collection

To do this, we first define documents and then use the insert() method, as shown below. To insert two documents in a collection named employees, type:

var beginners =
[
{
“EmployeeId” : 001,
“EmployeeName” : “Ludacris”,
“age”: 29
},
{
“ EmployeeId” : 002,
“ EmployeeName” : “Nelly”,
“age”: 36
},
];

db.students.insert(beginners);

Query document

We will use find() to query documents in a collection.

Querying documents in the JSON format: If we have a collection called employees in a database employeesbd, to get documents from it, use the command below:

db.employees.find()

We use JSON to enable a better output:

db.employees.find().forEach(printjson);

…or use the pretty() function:

db.employees.find().pretty()

Fetching documents using a criteria

This is useful when there are specific documents you want to fetch.

Example: Equality criteria
To fetch the data of Ludacris from the employees collection, type:

db.employees.find({EmployeeName : “Ludacris”}).pretty()

Example: Greater than criteria

The command syntax is:

db.collection_name.find({“field_name”:{$gt:criteria_value}}).pretty()

To fetch details of employees aged over 25:

db.employees.find({“age”:{$gt:25}}).pretty()

Example: Less than criteria
The command syntax is as follows:

db.collection_name.find({“field_name”:{$lt:criteria_value}}).pretty()

To fetch details of all employees who earn less than US$ 4000:

db.employees.find({“Score”:{$lt:4000}}).pretty()

Example: Not equal to criteria
The command syntax is:

db.collection_name.find({“field_name”:{$ne:criteria_value}}).pretty()

To get details of employees whose salary is not equal to US$ 3500:

db.employees.find({“Salary”:{$ne:3500}}).pretty()

Update document

To use the update() method, the command syntax is:

db.collection_name.update(criteria, update_data)

Example: Assuming I have a collection named movies in a database bestmoviesdb, the documents inside movies are:

> db.movies.find().pretty()
{
“_id” : ObjectId(“59bd2e9fce524b733f14dd67”),
“name” : “300”,
“genre” : thriller
}
{
“_id” : ObjectId(“59bd2ec5ce524b733f14dd68”),
“name” : “Avatar”,
“genre” : action
}

I now want to update the genre of Avatar to Fantasy from Action. The command syntax will be:

db.movies.update({“genre”:”action”},{$set:{“genre”:”fantasy”}})

Using the save() method to update, the command syntax is:

db.collection_name.save( {_id:ObjectId(), new_document} )

To use the save() method, it is important to know the unique _id field of the document you want to update. If one does not use the _id field here, the document is inserted as ‘new’ in the collection.

To get the _id of a document, run the following command:

db.got.find().pretty()

Once you have the unique _id of the field, run the following command to update it by using the save() method:

> db.movies.save({“_id” : ObjectId(“59bd2e73ce524b733f14dd65”), “name”:
“Avatar”, “genre”:fantasy})
>

Community, support and the future of MongoDB

The MongoDB community is one of the most diverse, robust, active and vibrant there is. While the community was able to interact on other platforms such as Slack, Realm forums, etc, and it still can, as of mid-2020, MongoDB created a unified forum that incorporates all its users so they can share their experiences, opinions and interact with each other. This forum has been created keeping in mind that MongoDB users operate both offline and online, and so must have support for that.

To log in or sign into this forum, you can use your MongoDB cloud account or register for one if you do not have one; or log in with a Google account. Once you log in, you can then set up your profile and keep in touch with the topics important to you.

There is also a welcome bot called Leafy that can assist with navigating the registration steps. Make sure you connect with other MongoDB members and enthusiasts.

LEAVE A REPLY

Please enter your comment!
Please enter your name here