Using MongoDB


MongoDB is a document-oriented NOSQL database application.
It is an open-source cross-platform which thus makes it a free database application.
MongoDB is developed by MongoDB Inc which started its development in 2007 and can be reached on the web through https://www.mongodb.com
It has some impressive features such as File storage with an efficient load balancing and data replication features over multiple machines for storing files.

 Hi guys
In this post we will be learning how to interact with MongoDB using its query engine via command prompt.
If you have gone through my earlier post on how to install MongoDB, then you should be ready for this. Please click here if you haven't seen the installation post
So lets begin......


Mongodb follows a server-client architecture. mongo.exe is the client, but before you can use the mongo.exe client you need to first of all start mongod.exe, which is the service that listens for client connection.

Note: Without starting mongod.exe, your connection to mongoDB will result in errors.

You can only run commands in your MongoDB enviroment. In my case, my enviroment is
C:\MongoDB\MDB\bin

We need to startup the MongoDB service to serve the client.
1. Open the Command propmt

2. Goto the MongoDB utility located in the following directory:
C:\MongoDB\MDB\bin
your queries will be ran from this location.

3. Type the following commands to start up the server:
mongod --logpath C:\MongoDB\LOG\activity.log --logappend

This will set the location where all logs files will be kept.


4. Type the following commands:
mongod --dbpath C:\MongoDB\DATA\DB

This will set the data path for the mongoDB server and prepare it for taking data. It will listen on port 27017


Now that we have successfully started the MongoDB service, we can now proceed to connect to the database.

5. To start writing queries, open a new command prompt.

6. Switch to the mongoDB enviroment (C:\MongoDB\MDB\bin), and then type the following comand.
mongo

This will initiate a mongo shell where you can input NoSQL queries

QUERY TIME

1. Lets clear the screen first of all. This can be done by typing the following command
cls


2. To see the list of all available databases type the following commands
show dbs


From the screenshot my mongoDB has 3 databases

  • admin
  • config
  • local

Creating a database in MongoDB
3. Now let us create a new database. Lets name our database  itcasxpdb
To do this simply type the command
use itcasxpdb

As you can see from the screenshot it not only created the database, it also switch to the database for us.

4. To confirm the current database you are in  type the following query:
db

Creating user in MongoDB
5. Now let create users for our database
MongoDB uses queries similar to JSON (JavaScript Object Notation) Language.

6. To create user we will use the db.createUser() method.
In this example, we will create the follwoign

  • A user called Olutayo 
  • A password of guess123
  • We will grant him admin privilege and 
  • Allow him to read and write into the database.

So lets begin

db.createUser(
{
user:"olutayo",
pwd:"guess123",
roles:["readWrite","dbAdmin"]
}
);


Creating Collections in MongoDB
In MongoDB Tables are called collections. So for every database created we must have collections to also help organise the data.

7. The db.createCollection(name, options) method is used to create collections in MongoDB
In the command, name is name of collection to be created. The Options parameter is optional, so you can specify only the name of the collection to have it successfully created.

8. Let us create a collection called STUDENTS. This will keep records of my students.
Type the following query:
db.createCollection('students');

9. To see all the collections in this database (itcasexp), type the following command:
show collections

Inserting into collections in MongoDB
10. Now that we have created our collection, its time to add data into it.
the method db.collection.insert() is used to perform inserts in MongoDB.

11. Type the following command:
db.students.insert(
{
first_name:"Damilola",
last_name:"Ajayi",
skills:"Application Development",
Qualifications: ['Bsc', 'Msc', 'OCP'],
Training_class: "Web application security"
}
);


You can see this is quite simple.
Please note that if you want to enter more than one entry in a field (as I did in the "Qualifications" field), you can express them as an array. This will require the use of the squared brackets [].

11. To query the data we just inserted into the students collection,
type the following command:
db.students.find();

Note that the output has a strange field which we did not insert
("_id" : ObjectId("5ac4cd5bfeead8bd085d108c")). 
This is a unique value used to distinguish the data. It is automatically created.
This is the uniqueness of Nosql database. With this automation there is no need to bother about sequences or constraints on your unique value as compared to Relational database.

12. Lets insert more data into our collection. This time lets add multiple data in one single command. This can be achieved with the squared brackets to manage your arrays.
Type the following commands:

db.students.insert(
[
{first_name:"Najeem",
last_name:"Oyeyemi",
skills:"Pentester",
Qualifications: ['Bsc', 'ITIL','CISA','COBIT5','CEH', 'OCP'],
Training_class: "IT Audit"},
{first_name:"Enitan",
last_name:"Daramola",
skills:"Application audit",
Qualifications: ['Bsc', 'ITIL','CISA'],
Training_class: "IT Audit"},
{first_name:"Thomas",
last_name:"Ebite",
skills:"IT Process Control",
Qualifications: ['Bsc', 'COBIT5','CISA','OCA'],
Training_class: "DevSecOps"},
{first_name:"Erioluwa",
last_name:"Oginni",
skills:"IT Process Control",
Qualifications: ['Bsc', 'ITIL','CISA'],
Training_class: "IT Audit"},
]
);


13. lets query our collection (students) to see the data inside.
Type the following command:
db.students.find();

Adding a field to a collection in MongoDB
The beauty of NoSQL is that you can add any field at anytime in your insert command without issues to the collection.
Lets see an example. I will add a "Remark" field to a new data I just inserted.
Type the following command
db.students.insert(
{
first_name:"Danjuma",
last_name:"Musa",
skills:"None",
Remark: "I am new to this class",
Qualifications: ['Bsc'],
Training_class: "IT Process Control"
}
);

14. MongoDB has this strange method which is used to put your data in an organised fashion. Its called .pretty() (can you imagine that????). Well it is appended to the db.students.find() method.
Lets have a look at this method. Type the follwing command:
db.students.find().pretty()

Wow!!!I like this arangement already. Its quite easy to read now.

Updating data in collections in MongoDB
Now supposing you want to update an existing data in any of your collections how would you do it? Lets see

15.  The method db.collection.update is used.
Let us try out an example by updating one of the users called Enitan who has a new skill (Database Security) added to her existing skill (Application audit).
The following command will be used:
db.students.update(
{_id: ObjectId("5ac4d3e3feead8bd085d108e")},
{first_name:"Enitan",
last_name:"Daramola",
skills:['Application audit','Database Security'],
Qualifications: ['Bsc', 'ITIL','CISA'],
Training_class: "IT Audit"}
);
Explanation

  • The db.students.update() method was used.
  • I wanted to update only Enitans data so I needed a unique value to search Enitans data out.
  • the _id which i explained to you earlier was automatically generated to make the data unique was the best choice.
  • Thus I used the _id which was ObjectId("5ac4d3e3feead8bd085d108e") as seen in the query.
  • Because I was updating by adding data to the skills field i had to express it in an array (since it is more that one entity). That was why I used the Square brackets.

Hope the explanation is simple enough.

Selecting specific data from a collection in MongoDB
16. Lets us see the data we just updated. In this command we will not just query all data, instead we will narrow our search down to the data of interest.
Type the following command:
db.students.find({_id: ObjectId("5ac4d3e3feead8bd085d108e")}).pretty()

You can see that I have searched with the unique value once again.

Removing a Field in MongoDB ($unset)
17. Recall we added a field (Remark) to our student collection.
Let us now remove the field completely as we do not need it anymore.
So how do we do this?
Simple!!
We use the $unset command
Here's how to use it. Lets go ahead to remove the field (Remark).
Type the following command:

db.students.update(
{_id: ObjectId("5ac4d628feead8bd085d1091")},{$unset:{Remark:""}}
);

18. Let us see if the field has really been removed. Type the following command:
db.students.find({_id: ObjectId("5ac4d628feead8bd085d1091")}).pretty()

Yep its gone

Remove a collection in MongoDB
To remove a collection in MongoDB requires the used of the following method:
db.collection.drop()
Lets see how its used

19. As an exercise, let us create a new collection and then drop it.
Type the following commands:

20. Create a collection called dummy_collection.
db.createCollection('dummy_collection');

21. Lets query to see the collection
show collections

22. Drop  the collection we just created.
db.dummy_collection.drop();

21. Lets query to see if the collection still exist
show collections

And that's how its done.

I hope you enjoyed this post if so please give me some thumbs up.

There are many more fun stuff to do on mongoDb that I honestly cannot cram into this post.
However I will provide links that can aid in further study for those very serious with NoSQL.

https://docs.mongodb.com/manual/reference/method/
https://www.tutorialspoint.com/mongodb/index.htm
https://university.mongodb.com/


Logos used in this blogs are extracted from their respective owners.

Comments

Post a Comment

Popular posts from this blog

Auditing Virtualization

How to Identify if the capacity of your FLASH storage device is genuine or counterfeit

Address Resolution Protocol (ARP): Understanding the basics