Learn NO-SQL Database (MongoDB)

#mongodb #install_mongodb #performance_mongodb #commands_mongodb

Rohit V Sept 27 2020 · 7 min read
Share this

When people use the term “NoSQL database”, they typically use it to refer to any non-relational database. Some say the term “NoSQL” stands for “non SQL” while others say it stands for “not only SQL.” Either way, most agree that NoSQL databases are databases that store data in a format other than relational tables.

A common misconception is that NoSQL databases or non-relational databases don’t store relationship data well. NoSQL databases can store relationship data—they just store it differently than relational databases do. In fact, when compared with SQL databases, many find modeling relationship data in NoSQL databases to be easier than in SQL databases, because related data doesn’t have to be split between tables.

NoSQL data models allow related data to be nested within a single data structure.

NoSQL databases emerged in the late 2000s as the cost of storage dramatically decreased. Gone were the days of needing to create a complex, difficult-to-manage data model simply for the purposes of reducing data duplication. Developers (rather than storage) were becoming the primary cost of software development, so NoSQL databases optimized for developer productivity.

https://cdn.jsdelivr.net/gh/matevarju89/cxl/noSQL.svg

Data Models

NoSQL databases often leverage data models more tailored to specific use cases, making them better at supporting those workloads than relational databases. For example, key-value databases support simple queries very efficiently while graph databases are the best for queries that involve identifying complex relationships between separate pieces of data.

Performance

NoSQL databases can often perform better than SQL/relational databases for your use case. For example, if you’re using a document database and are storing all the information about an object in the same document (so that it matches the objects in your code), the database only needs to go to one place for those queries. In a SQL database, the same query would likely involve joining multiple tables and records, which can dramatically impact performance while also slowing down how quickly developers write code.

Scalability

SQL/relational databases were originally designed to scale up and although there are ways to get them to scale out, those solutions are often bolt-ons, complicated, expensive to manage, and hard to evolve. Some core SQL functionality also only really works well when everything is on one server. In contrast, NoSQL databases are designed from the ground up to scale-out horizontally, making it much easier to maintain performance as your workload grows beyond the limits of a single server.

Data Distribution

Because NoSQL databases are designed from the ground up as distributed systems, they can more easily support a variety of business requirements. For example, suppose the business needs a globally distributed application that provides excellent performance to users all around the world. NoSQL databases can allow you to deploy a single distributed cluster to support that application and ensure low latency access to data from anywhere. This approach also makes it much easier to comply with data sovereignty mandates required by modern privacy regulations.

Reliability

NoSQL databases ensure high availability and uptime with native replication and built-in failover for self-healing, resilient database clusters. Similar failover systems can be set up for SQL databases but since the functionality is not native to the underlying database, this often means more resources to deploy and maintain a separate clustering layer that then takes longer to identify and recover from underlying systems failures.

Flexibility

NoSQL databases are better at allowing users to test new ideas and update data structures. For example, MongoDB, the leading document database, stores data in flexible, JSON-like documents, meaning fields can vary from document to document and the data structures can be easily changed over time, as application requirements evolve. This is a better fit for modern microservices architectures where developers are continuously integrating and deploying new application functionality.

MongoDB is a document-based, general purpose, distributed database with scalability and flexibility. And most of the features are free to use.

A. Features of MongoDB 

1. Rich JSON Documents

·       The most natural and productive way to work with data.

·       Supports arrays and nested objects as values.

·       Allows for flexible and dynamic schemas.

·       The document model maps to the objects in your application code, making data easy to work with.

2. Powerful query language

Rich and expressive query language that allows you to filter and sort by any field, no matter how nested it may be within a document.

·       Support for aggregations and other modern use-cases such as geo-based search, graph search, and text search.

·       Queries are themselves JSON, and thus easily compassable. No more concatenating strings to dynamically generate SQL queries.

3.  All the power of a relational database, and more...

·       Full ACID(Atomicity, Consistency, Isolation, Durability) transactions.

·       Support for joins in queries.

·       Two types of relationships instead of one: reference and embedded.

4. Charts

The fastest way to create visualizations of MongoDB data.

·       Built for the document model.

·       Visualize live data from any of your MongoDB instances. Available on MongoDB Atlas.

·       Visualize live data from any of your MongoDB instances. Available on MongoDB Atlas.

5. BI Connector

·       Allow any BI tool that can speak the MySQL protocol to work with your MongoDB data.

·       Leverage the BI tools your organization already uses.

·       Perform federated analytics, combining data from MongoDB and other databases.

6. Compass

https://docs.mongodb.com/compass/beta/query/filter/

MongoDB Architecture

B. Installing MongoDB

1.    Go to the page: https://www.mongodb.com/download-center/community and select the MongoDB installation to download based on your operating system.

2.    After the installer gets downloaded, double click on the installer file to start installing the application.

3.    Click on the next button to move to the next step and accept the agreement.

4.    Select the type of installation:

5.    Select the features to install.

6.    Click on next and then configure/customize the way you want the application to be installed.

7.    Click next and then click on install to start the MongoDB installation.

C. Starting MongoDB:

1.    Go the services section and then start the MongoDB service if not already started.

2.    Now, to check whether the database server is up or not, go to the bin directory of the MongoDB installation and run the ‘mongo’ command as shown. If the command runs successfully, it means that the server is up and running and we can proceed.

D. Some Commands in Mongo DB:

Different commands can be used for different purposes:

·      show dbs: to show all the databases

·      use <DBName>: creates a new database with the name if not already present or starts using the database given as database name.

·      db.createCollection(‘<collectionName>’) : to create a new collection. Collections are analogous to tables.

·      show collections to show all the collections in a database.

·      db.<collectionName>.insert({“key”:”value”}) : to insert new record into the table.

·      db.<collectionName>.find(): To show all the records from a table.

·      db.<collectionName>.update({“key”:”value”}, ({“key”:”new_value”}) : to update an existing record in the table.

·      db.<collectionName>.remove({“key”:”value”}) : to remove record(s) from the table matching the criteria.

E. Python Code Implementation:

Import pymongo  # package which enables us to connect to the MongoDB

dbConn = pymongo.MongoClient("mongodb://localhost:27017/")  # connecting to the locally running MongoDB Instance

db = dbConn['crawlerDB'] # connecting to the databse named crawlerDB present in the mongoDB

 mydict = {"Product": "samsung", "Name": "testName", "Rating": '3'} # creating key value pairs for inserting into the DB

collection=db['samsung']  # obtaining the collection name

x = collection.insert_one(mydict)  # inserting record into the collection

reviews= collection.find({})  # Finding all the records in the collection named Samsung

for review in reviews:

print("product: "+review['Product']+", "+"Name: "+review['Name']+", "+"Rating: "+review['Rating'])

Output:

product: samsung, Name: Karishma  Barah, Rating: 5

product: samsung, Name: Amritlal Baraia, Rating: 4

product: samsung, Name: Roshan Kumar  , Rating: 5

product: samsung, Name: Ameya Gaandhe, Rating: 5

product: samsung, Name: Aryan  Jadhav, Rating: 5

product: samsung, Name: Apurba  Mondal, Rating: 5

product: samsung, Name: Sourav, Rating: 5

product: samsung, Name: Flipkart Customer, Rating: 4

product: samsung, Name: Anand Jadhao, Rating: 5

product: samsung, Name: ANKIT  CHOUKSEY, Rating: 5

product: samsung, Name: No Name, Rating: No Rating

product: samsung, Name: testName, Rating: 3

F. Bonus: UI for MongoDB

If all these black screens(Command Line Interfaces) scare you, then MongoDB has an application called MongoDB Compass which provides a user interface where the databases and corresponding collections can be viewed. It also shows the performance of the database server.

You just have to download the MongoDB compass installation file and proceed with the installation as we did for MongoDB server.

·      Once the application gets installed, you can run it and connect to the already running database server as shown below:

•     Once you click on connect, it will show the following details:

·       Here, you can select the individual database to see the collections in that database. And similarly, a collection can be selected to see the records inside.

·       Clicking the performance tab shows different metrics related to performance:

-------------------------------------------------------------------------------------

References:

https://www.mongodb.com/nosql-explained

https://www.mongodb.com/try/download/community

https://www.mongodb.com/products/compass

I like to thank all the mentors who helped me to write this Blog.......

Comments
Read next