PL I – ASSIGNMENT 5

ASSIGNMENT NO.5

Title:  Implement database with suitable example using MongoDB and implement all basic operations and administration commands using two tier-architecture.

Requirements:

  1. Computer System with Windows 64/Linux/Open Source Operating System.
  2. MongoDB Client
  3. MongoDB Server

Theory:

Configuring MongoDB :

1) Download Mongodb 64 Bit version (32 bit version allows only 2GB database Size)

2) Extract in a folder.

3) Rename folder as mongodb

4) From Command Prompt, Goto bin directory in mongodb installation

5) Start mongod.exe file for starting mongodb server.

6) Use following uri in two tier architecture when you want to connect to server machine

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

7) Create data/db foder on same path where mongodb is installed

8) If path of data folder is different, use mongod.exe –dbpath “path of data folder”

9) Start command prompt and execute mongo.exe client file from bin folder of mongodb installation for starting client

MongoDB connection string to connect to MongoDB Server

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]

The URL format is unified across official drivers from 10gen with some options not supported on some drivers due to natural reasons. The ones not supported by the Node.js driver are left out for simplicities sake.

Basic parts of the url

mongodb:// is a required prefix to identify that this is a string in the standard connection format.

username:password@ is optional. If given, the driver will attempt to login to a database after connecting to a database server.

host1 is the only required part of the URI. It identifies either a hostname, IP address, or unix domain socket

:portX is optional and defaults to :27017 if not provided.

/database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the “admin” database will be used by default.

?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by “&”. For any unrecognized or unsupported option, a driver should log a warning and continue processing. A driver should not support any options that are not explicitly defined in this specification. This is in order to reduce the likelihood that different drivers will support overlapping that differ in small but incompatible ways (like different name, different values, or different default value).

The use Command : MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn’t exist otherwise it will return the existing database.

Syntax: Basic syntax of use DATABASE statement is as follows:

> use DATABASE_NAME

Example: If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:

>use mydb

switched to db mydb

To check your currently selected database use the command db

>db

mydb

The dropDatabase() Method: MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax: Basic syntax of dropDatabase() command is as follows:

>db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default ‘test’ database.

Example: First, check the list available databases by using the command show dbs

>show dbs

local      0.78125GB

mydb       0.23012GB

test       0.23012GB

If you want to delete new database <mydb>, then dropDatabase() command would be as follows:

>use mydb

switched to db mydb

>db.dropDatabase()

{ “dropped” : “mydb”, “ok” : 1 }

 

The createCollection() Method : MongoDB db.createCollection(name, options) is used to create collection.

Syntax: Basic syntax of createCollection() command is as follows

>db.createCollection(name, options)

In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection

Examples:

>use test

switched to db test

>db.createCollection(“mycollection”)

{ “ok” : 1 }

The drop() Method: MongoDB’s db.collection.drop() is used to drop a collection from the database.

Syntax: Basic syntax of drop() command is as follows

db.COLLECTION_NAME.drop()

Example: > db.mycollection.drop()

true

The insert() Method: To insert data into MongoDB collection, you need to use MongoDB’s insert() or save()method.

Syntax: Basic syntax of insert() command is as follows:

>db.COLLECTION_NAME.insert(document)

Example:

>db.mycol.insert({_id: ObjectId(7df78ad8902c), title: ‘MongoDB Overview’, description: ‘MongoDB is no sql database’, by: ‘point’, url: ‘http://www.MONGO.com’, tags: [‘mongodb’, ‘database’, ‘NoSQL’], likes: 100 })

Here mycol is our collection name, as created in previous tutorial. If the collection doesn’t exist in the database, then MongoDB will create this collection and then insert document into it.

MongoDB’s update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB Update() method: The update() method updates values in the existing document.

Syntax: Basic syntax of update() method is as follows

>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Following example will set the new title ‘New MongoDB Tutorial’ of the documents whose title is ‘MongoDB Overview’

>db.mycol.update({‘title’:’MongoDB Overview’},{$set:{‘title’:’New MongoDB Tutorial’}})

MongoDB Save() Method: The save() method replaces the existing document with the new document passed in save() method

Syntax: Basic syntax of mongodb save() method is shown below:

>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Example: Following example will replace the document with the _id ‘5983548781331adf45ec7’

>db.mycol.save({    “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tutorial New Topic”, “by”:”Tutorial”   } )

The remove() Method: MongoDB’s remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.

  1. deletion criteria : (Optional) deletion criteria according to documents will be removed.
  2. justOne : (Optional) if set to true or 1, then remove only one document.

Syntax: Basic syntax of remove() method is as follows

>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Following example will remove all the documents whose title is ‘MongoDB Overview’

>db.mycol.remove({‘title’:’MongoDB Overview’})

Remove only one : If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents : If you don’t specify deletion criteria, then mongodb will delete whole documents from the collection. This is equivalent of SQL’s truncate command.

>db.mycol.remove()

The find() Method : To query data from MongoDB collection, you need to use MongoDB’s find() method.

Syntax: Basic syntax of find() method is as follows

>db.COLLECTION_NAME.find()

AND in MongoDB

Syntax: In the find() method if you pass multiple keys by separating them by ‘,’ then MongoDB treats it AND condition. Basic syntax of AND is shown below:

>db.mycol.find({key1:value1, key2:value2}).pretty()

OR in MongoDB :

Syntax: To query documents based on the OR condition, you need to use $or keyword. Basic syntax of OR is shown below:

> db.mycol.find(   {      $or: [                    {key1: value1}, {key2:value2}      ]    } )

Conclusion: Hence we have studied basic operation commands of MongoDB in two tier architecture

********************** QUERIES *********************

AIM: Implement database with suitable example using MongoDB and implement all basic operations and administration commands using two tier architecture.

 > show dbs
admin  (empty)
local  0.078GB
te_a   0.078GB
 
> use te_a
switched to db te_a
 
> db.expt5.insert({"RNO" : 1, "NAME" : { "FIRST" : "SANDESH", "LNAME" : "GANGWAL" }, "ADDRESS" : { "CITY" : "PUNE", "DISTRICT" : "PUNE", "PIN" : 345678 }, "CONTACTNO" :[1234567,456788076] });
WriteResult({ "nInserted" : 1 })
 
> db.expt5.insert({"RNO" : 2, "NAME" : { "FIRST" : "ISHAAN", "LNAME" : "KOTHARI" }, "ADDRESS" : { "CITY" : "AMRAVATI", "DISTRICT" : "AMRAVATI", "PIN" : 444605 }, "CONTACTNO" : 789798797});
WriteResult({ "nInserted" : 1 })
 
> db.expt5.insert({"RNO" : 3, "NAME" : { "FIRST" : "AKASH", "LNAME" : "SUMEDH" }, "ADDRESS" : { "CITY" : "PUNE", "DISTRICT" : "PUNE", "PIN" : 444605 }, "CONTACTNO" :[34343444,789798797,356565665] ,   "EMAIL" : "jfsdkfj@dkfj.com"});
WriteResult({ "nInserted" : 1 })
 
> show collections
expt5
system.indexes
 
> db.expt5.find();
{ "_id" : ObjectId("541e3d71313dc145de686df5"), "RNO" : 2, "NAME" : { "FIRST" : "ISHAAN", "LNAME" : "KOTHARI" }, "ADDRESS" : { "CITY" : "AMRAVATI", "DISTRICT" : "AMRAVATI", "PIN" : 444605 }, "CONTACTNO" : 789798797 }
{ "_id" : ObjectId("541e3dcb313dc145de686df6"), "RNO" : 1, "NAME" : { "FIRST" : "SANDESH", "LNAME" : "GANGWAL" }, "ADDRESS" : { "CITY" : "PUNE", "DISTRICT" : "PUNE", "PIN" : 345678 }, "CONTACTNO" : [ 1234567, 456788076 ] }
{ "_id" : ObjectId("541e3e5a313dc145de686df7"), "RNO" : 3, "NAME" : { "FIRST" : "AKASH", "LNAME" : "SUMEDH" }, "ADDRESS" : { "CITY" : "PUNE", "DISTRICT" : "PUNE", "PIN" : 444605 }, "CONTACTNO" : [ 34343444, 789798797, 356565665 ],     "EMAIL" : "jfsdkfj@dkfj.com" }
 
> db.expt5.find().pretty();
{
      "_id" : ObjectId("541e3d71313dc145de686df5"),
      "RNO" : 2,
      "NAME" : {
            "FIRST" : "ISHAAN",
            "LNAME" : "KOTHARI"
      },
      "ADDRESS" : {
            "CITY" : "AMRAVATI",
            "DISTRICT" : "AMRAVATI",
            "PIN" : 444605
      },
      "CONTACTNO" : 789798797
}
{
      "_id" : ObjectId("541e3dcb313dc145de686df6"),
      "RNO" : 1,
      "NAME" : {
            "FIRST" : "SANDESH",
            "LNAME" : "GANGWAL"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
      "DISTRICT" : "PUNE",
            "PIN" : 345678
      },
      "CONTACTNO" : [         1234567,
            456788076   ]
}
{
"_id" : ObjectId("541e3e5a313dc145de686df7"),
      "RNO" : 3,
      "NAME" : {
            "FIRST" : "AKASH",
            "LNAME" : "SUMEDH"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
            "DISTRICT" : "PUNE",
            "PIN" : 444605
      },
      "CONTACTNO" : [
            34343444,
            789798797,
            356565665
      ]
      "EMAIL" : "jfsdkfj@dkfj.com"
}
 
> db.expt5.update({"NAME.LNAME":"SUMEDH"},{$set:{"NAME.LNAME":"KOTHARI"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.expt5.update({"ADDRESS.CITY":"PUNE"},{$set:{"CONTACTNO":8888888888}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.expt5.update({"ADDRESS.CITY":"PUNE"},{$set:{"CONTACTNO":8888888888}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })
 
> db.expt5.update({"RNO":{$gt:5}},{$set:{"CONTACTNO":8888888888}},{multi:true});
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
 
> db.expt5.update({"RNO":{$lt:5}},{$set:{"CONTACTNO":8888888888}},{multi:true});
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 1 })
 
> db.expt5.find().pretty();
{
      "_id" : ObjectId("541cfdb18a5439b34ba0b41a"),
      "RNO" : 1,
      "NAME" : {
            "FIRST" : "SANDESH",
            "LNAME" : "GANGWAL"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
            "DISTRICT" : "PUNE",
            "PIN" : 345678
      },
      "CONTACTNO" : 8888888888
}
{
      "_id" : ObjectId("541cfdec8a5439b34ba0b41b"),
      "RNO" : 2,
      "NAME" : {
            "FIRST" : "ISHAAN",
            "LNAME" : "KOTHARI"
      },
      "ADDRESS" : {
            "CITY" : "AMRAVATI",
            "DISTRICT" : "AMRAVATI",
            "PIN" : 444605
      },
      "CONTACTNO" : 8888888888
}
{
      "_id" : ObjectId("541cff058a5439b34ba0b41d"),
      "RNO" : 3,
      "NAME" : {
            "FIRST" : "AKASH",
            "LNAME" : "KOTHARI"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
            "DISTRICT" : "PUNE",
            "PIN" : 444605
      },
      "CONTACTNO" : 8888888888,
      "EMAIL" : "jfsdkfj@dkfj.com"
}
 
> db.expt5.remove({"ADDRESS.CITY":"AMRAVATI"});
WriteResult({ "nRemoved" : 1 })
 
> db.expt5.find().pretty();
{
      "_id" : ObjectId("541cfdb18a5439b34ba0b41a"),
      "RNO" : 1,
      "NAME" : {
            "FIRST" : "SANDESH",
            "LNAME" : "GANGWAL"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
            "DISTRICT" : "PUNE",
            "PIN" : 345678
      },
      "CONTACTNO" : 8888888888
}
{
      "_id" : ObjectId("541cff058a5439b34ba0b41d"),
      "RNO" : 3,
      "NAME" : {
            "FIRST" : "AKASH",
            "LNAME" : "KOTHARI"
      },
      "ADDRESS" : {
            "CITY" : "PUNE",
            "DISTRICT" : "PUNE",
            "PIN" : 444605
      },
      "CONTACTNO" : 8888888888,
      "EMAIL" : "jfsdkfj@dkfj.com"
}
 
> db.expt5.remove({"ADDRESS.CITY":"PUNE"},1);
WriteResult({ "nRemoved" : 1 })
 
> db.expt5.drop();
true
     
> db.dropDatabase();
{ "dropped" : "te_a", "ok" : 1 }

 

Leave a Reply

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