MongoDB
MongoDB is an open-source document database and leading NoSQL database. This tutorial give you great understanding on MongoDB concepts.
You need to download and install MongoDB from it’s official site. MongoDB
Basic commands on mongo shell
show all available database
show dbs;
Select a particular database to access, eg Student. This will create Employee if it does not already exists.
use Employee;
Show collection in database
show collections;
To check the currently selected database use the command db
db
Just type show dbs in your mongo shell and you will see available database
now type
use Employee;
and you will se it switched to database Employee
Just create user with username, password and roles with following lines of code
Now, we need to create collection. Collection may store a number of documents. A collection is analogous to a table of an RDBMS.
db.createCollection('Employee');
Now, let’s insert data into collection using MongoDB’s query
Inorder to see our data we need to write find() query
db.Employee.find()
this output as:
let’s pretify our document using preety() method. This is the method that pretty-prints resulting JSON.
We can use save instead of insert method. like
db.Employee.save({first_name:'Thyame', last_name:'Sedhai'});
The difference with save is that if the passed document contains an _id field, if a document already exists with that _id it will be updated instead of being added as new.
Here, insertOne is used to insert only one record and insertMany to insert multiple records.
db.Employee.insertMany([{first_name:'Diple', last_name:'pant', age:23}, {first_name:'Sid', last_name:'Nurse', age:23}]);
and you can see the output as:
Update
Now we can update the entire object
db.Employee.update({first_name:'Thyame'});
we can replace only first matching document. updateOne in new in MongoDB 3.2
db.Employee.updateOne({first_name:'Thyame'});
db.Employee.updateMany({first_name:'Thyame'}); //This replace all matching documents
we can update the field name by: We are updating Giri to lastname so before updating
db.Employee.update({Giri:'Nurse', {$rename:{Giri:'last_name'}}});
Now, after updating (writing above query) we get
If we want to change only the firstname field then we can use $set to specify which field we want to update.
db.Employee.update({first_name:'Thyame'}, {$set:{'first_name:'Ayush'}});
Delete
Deletes all documents matching the query parameters:
db.people.remove({first_name:'Sid'});
New in MongoDB 3.2
db.people.deleteMany({name: 'Sid'});
If we have multiple Employee’s with same and if we wish to remove only one name then we can write:
db.Employee.remove({first_name:'Sid'},{justone:true});
Comparison between MongoDB and SQL
The following table shows the SQL and MongoDB terminology
All documents from Employee collection
This is same as the
SELECT * FROM EMPLOYEE //from mysql Query
db.Employee.find({first_name:'Thyame'}).pretty();
will return document from our collection whose first_name is Thyame
this is same as the
SELECT * FROM EMPLOYEE WHERE FIRST_NAME = 'Thyame'; //in SQL query
AND queries
This is same as the
SELECT * FROM EMPLOYEE WHERE FIRST_NAME = 'Sid' AND age >= 23 ; //in SQL query
OR queries
This is same as the
SELECT * FROM EMPLOYEE WHERE FIRST_NAME = 'Sid' OR age >= 23 ; //in SQL query
PROJECTION
In MongoDB projection means selection only necessary data rather than selecting whole data of document.
The basic syntax of find() method with projection is as follows
db.COLLECTION_NAME.find({}, {age:0 });
In our case
db.Employee.find({}, {age:0 }).pretty();
This return all the documents without the age field
If you want to show only the age field then.
_id field is always appear when you write find() method if you don't need this field then you need to set id as 0;
1 is used to show the fields whereas 0 is used to hide the fields
Upsert
It is a boolean type. It’s default value is false. If it is set to true then it creates a new document when no document matches the query criteria
db.Employee.update({first_name:'Kedar'}, {first_name:'Kedar', last_name:'Sedai'},{upsert:true});
Tips about _id 😎
_id is a 12 bit hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you didn't provide MongoDB will provide a unique id for every document. First 4 byte for current timestamp next 3 byte for machine id next 2 byte for process id of mongoDB server and remaining 3 bytes for simple incremental value.
Increment and Decrement
we can Increment by using $inc
wheres as decrement is somehow tricky inorder to decrease we need to add negative value like $inc: -2 it will decrease by 2
Aggregation
Aggregation operations process data records and return computed results.
create some Dummy data:
db.Employee.insertMany([{name:'kedar', age:23, experience:'NO', languages:['Nepali','English']},{name:'sid',age:23, experience:'NO', languages:['Nepali','english','Hindi']}, {name:'Thyame', age:24, experience:'Yes',languages:['english','Nepali','Hindi']},{name:'Diple',age:23, experience:'yes', languages:['Nepali','Hindi','English']},{name:'Wishlist', age:24, experience:'yes', languages:['Nepali','English','German','Hindi']}]);
now inorder to get prettify collection we need to write
db.Employee.find().pretty();
and we get
Match is used to match the documents (like SQL where clause)
Project used to populate specific field’s value
db.Employee.aggregate([{$match:{experience:'NO'}}, {$project:{name:1, age:1}}]);
it will output as:
project will include _id field automatically unless you secify to disable it:
Sorting
Sorting by name in alphabatical order:
If we want to sort name in reverse order we just need to write -1