Learning NoSQL in analogous with SQL within 10 minutes, MongoDB — A Comparative Study

Learning NoSQL in analogous with SQL within 10 minutes, MongoDB — A Comparative Study

Learning NoSQL in analogous with SQL within 10 minutes, MongoDB — A Comparative Study

If one knows the SQL database, learning a NoSQL database is not a tough nut to crack. I will give you complete exposure regarding performing some general operations in NoSQL(using MongoDB as a NoSQL) which you already know how to achieve them in SQL.

Also, I will make you familiar with some extra services that are available in MongoDB which are absent in SQL such as adding some multimedia into the MongoDB using the GridFS.

Wait, I heard somebody said — I don’t speak SQL?

Well! Hold on and cheers 🍻 You got an additional bonus. As you will proceed until the end of this article with me, you will be able to learn both the SQL and the NoSQL under 10 minutes.

Alright! Are You Ready to Uncover the Hidden Treasure?

….
Yes? 
….
Okay, So, let’s roll …

First things first, so, here are quite essential points that pitch onto my mind whenever I think about the SQL and the NoSQL.

What is SQL?

  1. SQL pronounced as “S-Q-L” or sometimes as “See-Quel” popularly known as “Structured Query Language” is a relational database.
  2. SQL is widely used for storing and retrieving an immense amount of structured data.
  3. The data inside the database is stored in the form of tables which contains rows and columns and has a static schema.
  4. The ACID acronym is used to describe the properties of SQL databases. ACID can be expanded as “Atomicity Consistency Isolation Durability.”

What is NoSQL?

  1. NoSQL is popularly known as “Not only SQL database” is a non-relational database.
  2. NoSQL is widely used for storing and retrieving an immense amount of unstructured data and has a dynamic schema.
  3. The data inside the database is stored in the form of collections which contains documents.
  4. NoSQL employs key-value pairs method to store the information inside the document.
  5. The BASE acronym is used to describe the properties of NoSQL databases. The BASE can be expanded as “Basically Available, Soft state, Eventual consistency.”

So, what are the meat-and-potatoes for MongoDB?

  • Buckets in NoSQL are like schemas in relational databases.
  • Collections in NoSQL are like tables in relational databases.
  • Documents in NoSQL are like records(rows) in relational databases.

Some popular instance of NoSQL databases is MongoDB, HBase, Cassandra. Here, we’re going to explore about MongoDB

MongoDB

  1. MongoDB is a NoSQL database written in C++ language. So, since, it is NoSQL database the smallest unit in MongoDB is a document, documents are stored in a collection, which in turn forms up a database, there can be multiple collections.
  2. Not every document needs to have the same structure, each of them can have different fields, and that is a handy feature in many situations. Another feature of MongoDB is that areas in a document can contain arrays and or sub-documents (sometimes called nested or embedded documents).
  3. The documents inside the MongoDB is stored in the binary-encoded format called BSON(Binary encoded JSON) which is an extension of JSON.
    > Every BSON has a variable “_id” which uniquely identifies a document from the other documents within a collection.
    > The value of “_id” can be provided manually, if not provided it is always generated by the system which is a 12 bytes hexadecimal value. 
    > Every BSON document can have a maximum size of 16 MB.
  4. To store the data structure or objects into the file, we make use of a mechanism called Serialization(also called as marshaling of an object)
  5. To retrieve the data structure or objects from the file, we make use of a mechanism called De-serialization(also called as unmarshaling of an object).
  6. The MongoDB client drivers perform the serialization and de-serialization.

So far, so good, now, we have enough theory on the plate.
Let’s get down to business.

SQL vs MongoDB Operations

All the operations will be performed inside the MongoDB Shell. Make sure your MongoDB server is up and running and also you are inside the MongoDB shell.

Creating a database

Like create keyword in SQL, use keyword is used to create a database in MongoDB.
Syntax: use DATABASE_NAME 
Example: >use customers

  • To check-in which database you are currently at, use the command db
  • To list all the databases, use the command show dbs

Dropping(or Deleting) a database

Like SQL drop database statement is used to drop an existing database in SQL schema, MongoDB db.dropDatabase() command is used to drop the existing database.
Syntax: db.dropDatabase() 
Example: If you are inside the customers database, db.dropDatabase() will drop the customers database.

Creating a collection

Like create table statement is used to create a new table in SQL, db.createCollection(collection_name) is used to create collection in MongoDB.
Syntax: db.createCollection(COLLECTION_NAME) 
Example: >db.createCollection('users')

  • To list all the collections in the current database, use the command
    show collections

Dropping a collection

Like drop table table_name statement is used to drop a table in SQL, db.collection.drop() method is used to drop a collection from the database in MongoDB.
Syntax: db.collection.drop()
Example: db.users.drop() will drop the users collection from the database.

Inserting a document in the collection

Like insert into statement is used to add a new row of data to a table in the SQL database, MongoDB’s insert() or save() method is used to insert a document or documents into the MongoDB collection.
Syntax: db.collection.insert(DOCUMENT)
Example:
>db.users.insert({ "fname": "john", "lname": "doe", "sex": "male"}, { "fname": "mary", "lname": "laurine", "sex": "female"})

  • The MongoDB’s, insertOne method is used to insert a document into a collection.
    Syntax: db.collection.insertOne(DOCUMENT)
    Example:
    >db.users.insertOne({ "fname": "sankalp", "lname": "saxena", "sex": "male"})

Listing all the document in the collection

Like select command in SQL is used to list all the rows in a table, MongoDB’s find() method is used to list all the document from the MongoDB collection.
Syntax: db.collection.find() 
Example:>db.users.find() lists all the documents present in the users collection.

  • Like where clause in SQL is used to filter records from a table, specifying a key-value pair inside the find() in MongoDB is used to filter the document.
    Syntax: db.collection.find({KEY: VALUE}) 
    Example:>db.users.find({"fname": "sankalp"}) filter the documents from the users collection having fname as sankalp.
  • $or operator
    The $or operator is used to find multiple documents with multiple values for the same field.
    Syntax: {$or: [{<expression1>}, {<expression2>}, ..,{<expressionN>}]
    Example: db.users.find({$or: [{"fname": "sankalp"}, {"fname": "mary"}]}) filters the documents from the users collection having name either fname as sankalp or mary.
  • count() 
    count()
    is used to count the number of documents present in a collection.
    Syntax: db.collection.find().count()
    Example:>db.users.find().count() counts the number of documents present in the users collection.
  • limit()
    limit()
    is used to specify the maximum number of results to be returned.
    Syntax: db.collection().find().limit(NUMBER_OF_RECORDS)
    Example: >db.users.find().limit(4) returns first four documents present in the users collection.
  • sort()
    sort()
    is used to sort the documents in ascending or descending order based on a particular field of a document.
    Syntax: db.collection.find().sort({FIELD_KEY: 1 or -1}) 
    Example: >db.users.find().sort({"fname": 1}) Sorts the documents present in the users collection in ascending order with the field fname. 
    fname: 1 sorts the documents in ascending order of fname.
    fname:-1 sorts the documents in descending order of fname.
  • forEach()
    We can iterate through the documents in the collection using forEach(). It takes a custom defined function in which we can provide the logic for printing the document in the custom format.
    Syntax:
    db.collection.find().forEach(<function>)
    Example: db.users.find().forEach(function(object){ print("Fname: " + object.fname)}) iterates through all the documents in the collection users and prints fname of the customers using the custom print statement.

Comparison Query Operation
Syntax:
{<field>: {$OPERATOR: <value>}} 
$OPERATOR
can take any of the following values:

  • $eqMatches values that are equal to a specified value.
  • $gt Matches values that are greater than a specified value.
  • $gte Matches values that are greater than or equal to a specified value.
  • $in Matches any of the values specified in an array.
  • $lt Matches values that are less than a specified value.
  • $lte Matches values that are less than or equal to a specified value.
  • $ne Matches all values that are not equal to a specified value.
  • $nin Matches none of the values specified in an array.

Example: db.users.find({"age": {$lt: 40}}) returns all the documents from the users collection having age < 40

Prettifying the retrieved documents from the collection

The pretty() method of MongoDB, prettifies the BSON documents retrieved from the MongoDB collection and makes your documents more readable. 
Syntax: db.collection.find().pretty() 
Example:>db.users.find().pretty() lists all the documents present in the users collection with the BSON properly indented.

Updating the fields in the documents

Like update statement in SQL is used to modify the existing records in a table, MongoDB’s update() method modifies an existing document or documents in a collection.
Syntax: db.collection.update({QUERY}, {UPDATE}) 
Example:>db.users.update({"fname": "mary"}, {"fname": "mary", "lname": "laurine", "sex": "female", "age": 49}) updates the document having fname as mary with a new value {“age”: 49}. 
You need to specify the existing fields also otherwise they will be deleted.”

  • $set operator
    The update() method of MongoDB deletes the previous fields, so you need to mention it again or can use $set operator to retain those fields.
    Specifying {$set: {NEW_KEY: NEW_VALUE}} inside the find() method keeps whatever previously data was in there and also add a new specified field.
    Example: db.users.update({"fname": “mary"}, {$set: {"age": 49}}) adds a new field {“age”: 49} in the document having fname as mary also retaining the existing fields.
  • $inc operator
    The $inc operator is used to increment the value of a numeric or an integer field present within the document.
    Specifying {$set: {EXISTING_KEY: INCREMENT_VALUE}} inside the find() method increments the value of EXISTING_KEY by INCREMENT_VALUE.
    Example: db.users.update({"fname": "mary"}, {$inc: {"age": 5}}) updates the age field value from {“age”: 49} to {“age”: 54} in the document having fname as mary.
  • $unset operator
    The $unset operator is used to remove a particular field present within the document.
    Specifying {$unset: {FIELD: 1}} inside the find() method removes the FIELD present within the document.
    Example: db.users.update({"fname": "mary"}, {$unset: {"age": 1}}) removes the field “age” present inside the document having fname as mary.
  • $upsert operator
    The $upsert operator creates a new document when no document matches the query criteria. 
    If you try to modify some field in the document and if the document does not exist, you can insert it as a new document by setting the option upsert: true.
    Syntax: db.collection.update(QUERY, UPDATE, {$upsert: true})
    Example: db.users.update({"fname": "mary"}, {"fname": "alessandra"}, {$upsert: true}) queries the users collection for a document having fname as mary and tries to update it with new values if exists, if the document does not exist then it upsert option directly creates a new document with values same as the updated values specified.
  • $rename operator
    The $rename operator is used to rename some field present in the document to a new name.
    Specifying {$rename: {OLD_NAME1: NEW_NAME1, OLD_NAME2: NEW_NAME2, ...}} Inside the update() method renames OLD_NAME1 to NEW_NAME1, OLD_NAME2 to NEW_NAME2 and so on …
    Example: db.users.update({"fname": "mary"}, {$rename: {"fname": "First_Name", "lname": "Last_Name"}}) updates the field names “fname” to “First_Name” and “lname” to “Last_Name” present inside the document having fname as mary.

Removing a document

Like, delete statement in SQL is used to delete existing records in a table, of MongoDB’s remove() method removes documents from a collection.
Syntax: db.collection.remove({KEY: VALUE})
Example:>db.users.remove({"fname": "sankalp"}) remove the document from the users collection having fname as sankalp.

Exiting from the database

The exit command is used to come out of the MongoDB database.
Syntax: exit

Juggling multimedia files with MongoDB

Storing multimedia files inside MongoDB

Unlike SQL we can store multimedia files(often called as Blob files or Binary Large Object files) such as audio, video, images, gifs directly inside the MongoDB. As the size of the BSON document can be maximum stretched up to 16MB, MongoDB provides a special API called GridFS to store the multimedia having a size greater than 16MB.

How do GridFS API works?

Instead of storing a file in a single document, GridFS divides the blob files(a file having the size greater than 16 MB) into smaller chunks, and stores each chunk as a separate document. By default, GridFS uses a default chunk size of 255 kB

GridFS — The ultimate charm

GridFS makes use of the two collections to store Blob files. One collection stores the file chunks, and the other stores file metadata. These collections are named as:

  1. fs.files stores the metadata about the files that have been stored in the form of chunks inside fs.chunks.
  2. fs.chunks stores the actual files in binary format.

Steps to insert an image (a multimedia file) to the MongoDB’s collection

  • Go to the bin folder of your MongoDB and open the terminal.
➜  bin
  • Copy the absolute path of the image you want to store it to the database.
  • Fire the following command in terminal:
mongofiles -d gridfs put YOUR_IMAGE_FILE_PATH

Example: I want to add an image named “image.jpg” to the MongoDB which is present at my Desktop. Here is the absolute path to my image “/Users/Sankalp/Desktop/image.jpg” So, I place this pathname in the above command.

  bin mongofiles -d gridfs put /Users/Sankalp/Desktop/image.jpg
2019-07-19T01:12:08.535+0530 connected to: localhost
2019-07-19T01:12:08.537+0530 added file:
/Users/Sankalp/Desktop/image.jpg
  • MongoDB will create the database gridfs if it is not already present.
  • You can use these commands inside the MongoDB shell to view the data inside the fs.files and fs.chunks collections.
> use gridfs
switched to db gridfs
> show collections
fs.chunks
fs.files
> db.fs.files.find().pretty()
{
"_id" : ObjectId("5d30cd586f806cce7a5af116"),
"chunkSize" : 261120,
"uploadDate" : ISODate("2019-07-18T19:49:44.699Z"),
"length" : 134481,
"md5" : "4945952e1714eeb63da8aa51e93f7d3a",
"filename" : "/Users/Sankalp/Desktop/image.jpg"
}
> db.fs.chunks.find().pretty()
{
"_id" : ObjectId("5d30cd586f806cce7a5af117"),
"files_id" : ObjectId("5d30cd586f806cce7a5af116"),
"n" : 0,
"data":BinData(0,"/9j/AH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAADTLW)
}

Similarly, you can store any multimedia files inside the MongoDB using the GridFS.

Woohoo~! 🎉

We are done for today, now. I hope this article suffices you to comprehend about the nuts and bolts of the MongoDB, gracefully.

I will leave the floor open for the questions. 
Kindly, post them in the comment box, I will be happy to answer each one of those.

What am I missing here? Any tips to share? Let me know in the comments, and I’ll add it in!

Loved this article? Then make sure you give it a clap
Feel free to share the article if, at all you feel, it was worth reading it.

Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *