MongoDB_Basics

MONGODB
-----------------
MongoDB is a document-oriented database system (a kind of NoSQL) made up of the hierarchy of database > collection > document > field > key:value. Here is an approximate comparison between MongoDB and SQL data models.

MongoDB --------------SQL
database ------------- database
collection ------------ table
document ------------row
field ------------------X
{key:value} ----------X

Note: the Mongo shell is a fully functional JavaScript shell. You can perform JavaScript operations on data before inserting to or retrieving from the database. The shell supports all standard JavaScript API along with some Mongo-specific custom APIs. I think this feature makes MongoDB an extremely powerful and fascinating database system.

Innstalation Proces
==========================

https://www.liquidweb.com/kb/how-to-install-mongodb-on-centos-6/


$su root
$pwd:cloudera
[cloudera@quickstart /]$ cd /etc
[cloudera@quickstart etc]$ cd /etc/yum.repos.d

Create file
--------------------
$ gedit 10gen
[10gen]
name=10gen BRepository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1

save

after
$yuminstall mongo-10gen mongo-10gen-server


$service mongod start  or mongod

$mongo


commands
------------------------------------------------------------------
> show dbs             : list out all databases(database contain atleast one collection)
dbname  size
 like product  0.99GB
ourdb     0.12GB

> use dbname      : To select a database ,To create a database(First checking is it avaliable then select other wise create  and select)
use ourdb

>db.getName ()    : To show the current database (or)
>db
ourdb

>db.dropDatabase() : delete or drop the current database


> db.createCollection("emp")

>show collections :list out the all collection in the given database (or)
>show.getCollectionNames
employee
students

>db.employee.drop() :It will return true, if the selected collection is dropped successfully, otherwise it will return false.

Practice
------------------------------------------------------------------------
> show dbs
admin  (empty)
local  0.078GB

> use mydb
switched to db mydb

> show dbs
admin  (empty)
local  0.078GB

> db
mydb

> db.getName()
mydb

db.createCollection(name, options):-
=============================
> db.createCollection("sample",{capped:true,autoIndex:true,size:50,max:2})
{ "ok" : 1 }

> show collections
emp
sample
student
system.indexes

> db.sample.insert({_id:1,name:"gnr"})
WriteResult({ "nInserted" : 1 })
> db.sample.insert({_id:2,name:"gnrc",loc:"hyd"})
WriteResult({ "nInserted" : 1 })

> db.sample.find()
{ "_id" : 1, "name" : "gnr" }
{ "_id" : 2, "name" : "gnrc", "loc" : "hyd" }

> db.sample.insert({_id:3,name:"kiran",loc:"guntur"})
WriteResult({ "nInserted" : 1 })

> db.sample.find()
{ "_id" : 2, "name" : "gnrc", "loc" : "hyd" }
{ "_id" : 3, "name" : "kiran", "loc" : "guntur" }

> db.sample.drop()



 insert one document
---------------------------------
> db.student.insert({ _id:101, name:"lakshman", age:25, loc:"vinukonda", gen:"m" })
 WriteResult({ "nInserted" : 1 })

> show dbs
admin  (empty)
local  0.078GB
mydb   0.078GB

inserting multple documents
---------------------------------------------------
> db.student.insert(
... {_id:102,name:"ashok",age:24,loc:"vijayawada",gen:"m"},
... {_id:103,name:"sai",loc:"markapur"}
... )
WriteResult({ "nInserted" : 1 })




> db.student.insert({ _id:104, name:"gnr", qual:["bsc","mca"], loc:"guntur" })
WriteResult({ "nInserted" : 1 })
> db.student.insert({ name:"nag",_id:100, qual:["bsc","mca"], loc:"guntur" })
WriteResult({ "nInserted" : 1 })
> db.student.insert({ name:"unlnown" })
WriteResult({ "nInserted" : 1 })
> db.student.insert({_id:105,name:"gnrc",age:23,lover:{name:"vlp",age:22,loc:"guntur"},loc:"hyd" })
WriteResult({ "nInserted" : 1 })

> show collections
student
system.indexes
(or)
> db.getCollectionNames()
[ "student", "system.indexes" ]


Read Data from Collection
------------------------------------------------------
> db.student.find()
{ "_id" : 101, "name" : "lakshman", "age" : 25, "loc" : "vinukonda", "gen" : "m" }
{ "_id" : 102, "name" : "ashok", "age" : 24, "loc" : "vijayawada", "gen" : "m" }
{ "_id" : 104, "name" : "gnr", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }
{ "_id" : 100, "name" : "nag", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }
{ "_id" : ObjectId("58a5bb580f52bca5ef53ebef"), "name" : "unlnown" }
{ "_id" : 105, "name" : "gnrc", "age" : 23, "lover" : { "name" : "vlp", "age" : 22, "loc" : "guntur" }, "loc" : "hyd" }


> db.student.find().pretty()
{
"_id" : 101,
"name" : "lakshman",
"age" : 25,
"loc" : "vinukonda",
"gen" : "m"
}
{
"_id" : 102,
"name" : "ashok",
"age" : 24,
"loc" : "vijayawada",
"gen" : "m"
}
{
"_id" : 104,
"name" : "gnr",
"qual" : [
"bsc",
"mca"
],
"loc" : "guntur"
}
{
"_id" : 100,
"name" : "nag",
"qual" : [
"bsc",
"mca"
],
"loc" : "guntur"
}
{ "_id" : ObjectId("58a5bb580f52bca5ef53ebef"), "name" : "unlnown" }
{
"_id" : 105,
"name" : "gnrc",
"age" : 23,
"lover" : {
"name" : "vlp",
"age" : 22,
"loc" : "guntur"
},
"loc" : "hyd"
}

Only first Documnet
----------------------------------
> db.student.findOne()
{
"_id" : 101,
"name" : "lakshman",
"age" : 25,
"loc" : "vinukonda",
"gen" : "m"
}
(or)

> db.student.find().limit(1)
{ "_id" : 101, "name" : "lakshman", "age" : 25, "loc" : "vinukonda", "gen" : "m" }


> db.student.find().limit(3)
{ "_id" : 101, "name" : "lakshman", "age" : 25, "loc" : "vinukonda", "gen" : "m" }
{ "_id" : 102, "name" : "ashok", "age" : 24, "loc" : "vijayawada", "gen" : "m" }
{ "_id" : 104, "name" : "gnr", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }


> db.student.save({ _id:104, name:"srinu", qual:["mca","bsc"], loc:"vijayawada" })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Note:
db.student.save    option then   verify _id  is alerady there then update the document otherwise insert the documnet
db.student.insert option then verify _id is there then error(duplicate key error) otherwise insert the document

find()  function:
--------------------------------
find({},{}) function takes two arguments
first argument      ---- Query
second argument-----Projection   (here specify field names like
fieldname:number   here number is zero(0) then except that field  otherwise include that field 
filedname:true or false  here true means include that column flase means except that cloumn
> db.student.find({},{})
    all documents will be displayed

> db.student.findOne({},{name:true})
{ "_id" : 101, "name" : "lakshman" }

> db.student.find({},{name:true}).limit(2)
{ "_id" : 101, "name" : "lakshman" }
{ "_id" : 102, "name" : "ashok" }

> db.student.find({age:24})
{ "_id" : 102, "name" : "ashok", "age" : 24, "loc" : "vijayawada", "gen" : "m" }

> db.student.find({age:24},{name:1})
{ "_id" : 102, "name" : "ashok" }

> db.student.find({age:{$gte:24}},{name:1,age:true})
{ "_id" : 101, "name" : "lakshman", "age" : 25 }
{ "_id" : 102, "name" : "ashok", "age" : 24 }


>db.student.find({$and:[{name:"ashok"},{age:24}]},{name:1,age:true})   //select name,age from student where name='ashok' and age:24
{ "_id" : 102, "name" : "ashok", "age" : 24 }
(or)
> db.student.find({$and:[{name:"ashok"},{age:24}]},{name:1,age:true}) //select name,age from student where name='ashok' and age:24
{ "_id" : 102, "name" : "ashok", "age" : 24 }

> db.student.find({$or:[{name:"ashok"},{age:25}]},{name:1,age:true})  //select name,age from student where name='ashok' or age=25
{ "_id" : 101, "name" : "lakshman", "age" : 25 }
{ "_id" : 102, "name" : "ashok", "age" : 24 }

> db.student.find({$or:[{name:"ashok"},{age:{$gte:23}}]},{name:1,age:true})   //select name,age from student where name='ashok' or age>23
{ "_id" : 101, "name" : "lakshman", "age" : 25 }
{ "_id" : 102, "name" : "ashok", "age" : 24 }
{ "_id" : 105, "name" : "gnrc", "age" : 23 }

> db.student.find({_id:105},{name:1,"lover.name":1})
{ "_id" : 105, "name" : "gnrc", "lover" : { "name" : "vlp" } }


Feteching Query from Embeded fields
-----------------------------------------------------------------------------
> db.student.find({"lover.name":"vlp"})
{ "_id" : 105, "name" : "gnrc", "age" : 23, "lover" : { "name" : "vlp", "age" : 22, "loc" : "guntur" }, "loc" : "hyd" }


> db.student.find({qual:"mca"})
{ "_id" : 104, "name" : "srinu", "qual" : [ "mca", "bsc" ], "loc" : "vijayawada" }
{ "_id" : 100, "name" : "nag", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }
{ "_id" : 106, "name" : "ajay", "qual" : "mca", "loc" : "vijayawada" }

> db.student.find({qual:["mca","bsc"]})    //Exact match qual order
{ "_id" : 104, "name" : "srinu", "qual" : [ "mca", "bsc" ], "loc" : "vijayawada" }

> db.student.find({qual:["bsc","mca"]})  //Exact match qual order
{ "_id" : 100, "name" : "nag", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }

> db.student.find({qual:{$all:["bsc","mca"]}})  //Array it contain or not
{ "_id" : 104, "name" : "srinu", "qual" : [ "mca", "bsc" ], "loc" : "vijayawada" }
{ "_id" : 100, "name" : "nag", "qual" : [ "bsc", "mca" ], "loc" : "guntur" }


----------------------------------------------------------------------------------------------------------------------------------------------------------
> db.student.find({},{age:1})
{ "_id" : 102, "age" : 24 }
{ "_id" : 104 }
{ "_id" : 100 }
{ "_id" : 105, "age" : 23 }
{ "_id" : 106 }
{ "_id" : 101, "age" : 25 }
{ "_id" : 103, "age" : 25 }
{ "_id" : 107, "age" : 28 }
{ "_id" : 108, "age" : 20 }

> db.student.find({},{age:1,_id:0})
{ "age" : 24 }
{  }
{  }
{ "age" : 23 }
{  }
{ "age" : 25 }
{ "age" : 25 }
{ "age" : 28 }
{ "age" : 20 }

> db.student.find({},{age:1,_id:0,name:true})
{ "name" : "ashok", "age" : 24 }
{ "name" : "srinu" }
{ "name" : "nag" }
{ "name" : "gnrc", "age" : 23 }
{ "name" : "ajay" }
{ "name" : "lakshman", "age" : 25 }
{ "name" : "ramu", "age" : 25 }
{ "name" : "saikumar", "age" : 28 }
{ "name" : "saikumar", "age" : 20 }



Filtering Data
-------------------------------------------------------------------------------
Operators
------------------------------
deptno=10   -->  deptno:10
deptno!=10 --> deptno:{$ne:10}
deptno<10 -->deptno:{$lt:10}
deptno<=10 -->deptno:{$lte:10}
deptno>10 -->deptno:{$gt:10}
deptno>=10 -->deptno:{$gte:10}

> db.student.find({age:25},{age:1,_id:0,name:true})
{ "name" : "lakshman", "age" : 25 }
{ "name" : "ramu", "age" : 25 }

> db.student.find({age:{$ne:25}},{age:1,_id:0,name:true})
{ "name" : "ashok", "age" : 24 }
{ "name" : "srinu" }
{ "name" : "nag" }
{ "name" : "gnrc", "age" : 23 }
{ "name" : "ajay" }
{ "name" : "saikumar", "age" : 28 }
{ "name" : "saikumar", "age" : 20 }

***********AND*****************OR******************
-----------------------------------------------------------------------------------
> db.student.find({age:25},{age:1,_id:0,name:true})   //age = 25
{ "name" : "lakshman", "age" : 25 }
{ "name" : "ramu", "age" : 25 }

> db.student.find({age:25,name:'ramu'},{age:1,_id:0,name:true})   //passing multiplie values by separating , then it ttreated as AND   (age=25 and name='ramu')
  { "name" : "ramu", "age" : 25 } 

>db.student.find({$and:[{age:25},{name:"ramu"}]},{age:1,_id:0,name:true})  //By using and      (age=25 and name='ramu')
{ "name" : "ramu", "age" : 25 }

> db.student.find({$or:[{age:25},{name:"ramu"}]},{age:1,_id:0,name:true})  //by using or       (age=25 or name='ramu')
{ "name" : "lakshman", "age" : 25 }
{ "name" : "ramu", "age" : 25 }

> db.student.find({age:{$gt:23}},{age:1,_id:0})
{ "age" : 24 }
{ "age" : 25 }
{ "age" : 25 }
{ "age" : 28 }

> db.student.find({age:{$lt:26}},{age:1,_id:0})
{ "age" : 24 }
{ "age" : 23 }
{ "age" : 25 }
{ "age" : 25 }
{ "age" : 20 }


> db.student.find({age:{$gte:23},age:{$lte:26}},{age:1,_id:0})   
{ "age" : 24 }
{ "age" : 23 }
{ "age" : 25 }
{ "age" : 25 }
{ "age" : 20 }

> db.student.find({$and:[{age:{$gte:23}},{age:{$lte:26}}]},{age:1,_id:0})  //including range of values   (age>=23 and age<=26)
{ "age" : 24 }
{ "age" : 25 }
{ "age" : 25 }

> db.student.find({$or:[{age:{$lt:24}},{age:{$gt:26}}]},{_id:0,age:1,name:true})  //Excluding range of values    (age<24 or age>26)
{ "name" : "gnrc", "age" : 23 }
{ "name" : "saikumar", "age" : 28 }
{ "name" : "saikumar", "age" : 20 }

> db.student.find({name:"gnrc",$or:[{age:{$lt:24}},{age:{$gt:26}}]},{_id:0,age:1,name:true})   //   (name='gnrc' and (age<24 or age>26))
{ "name" : "gnrc", "age" : 23 }
(OR)
> db.student.find({$and:[{name:"gnrc"},{$or:[{age:{$lt:24}},{age:{$gt:26}}]}]},{_id:0,age:1,name:true})  // (name='gnrc' and (age<24 or age>26))
{ "name" : "gnrc", "age" : 23 }

> db.student.find({$or:[{name:"lakshman"},{$or:[{age:{$lt:24}},{age:{$gt:26}}]}]},{_id:0,age:1,name:true})  //(name='gnrc' or  (age<24 or age>26))
{ "name" : "gnrc", "age" : 23 }
{ "name" : "lakshman", "age" : 25 }
{ "name" : "saikumar", "age" : 28 }
{ "name" : "saikumar", "age" : 20 }

======================================================================================================================================
Update() Method
-------------------------
Syntax:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   } )
1.First parameter in MongoDB update is query that gives us the target rows – for example {country:"USA"} to get all documents where country is USA
2.Second parameter in MongoDB update is used to define the list of fields to update, for example we can use {name:"Pankaj Updated"} to update the name.
3.Other options in MongoDB update are optional but important too;
-->if  'upsert'  is specified as true then update query will insert a document if there are no matches to the query, default value is false.
--->if  'multi' is specified as true then all the documents that matches the query criteria will be updated, default value is false.
-->'writeConcern'  can be used to specify write concern, if not provided default write concern will be used.


MongoDB Update Document Operators
-------------------------------------------------
We have many mongo update parameter operators available – most widely used are $set, $inc, $currentDate.


NAME                                     DESCRIPTION
$inc +1 or -1             Increments the value of the field by the specified amount.
$mul             Multiplies the value of the field by the specified amount.
$rename             Renames a field.
$setOnInsert      Sets the value of a field upon document creation during an upsert.  Has no effect on update operations that modify existing documents.
$set            Sets the value of a field in a document.
$unset           Removes the specified field from a document.
$min           Only updates the field if the specified value is less than the existing field value.
$max           Only updates the field if the specified value is greater than the existing field value.
$currentDate     Sets the value of a field to current date, either as a Date or a Timestamp.


inserting documnets
---------------------------
> db.emp.insert({_id:100,name:'king',sal:5000},{name:'miller',sal:3000,_id:101},{_id:102,name:'ramu',sal:3000},{_id:103,name:'gnr',sal:6000})

Retriving Documnets
----------------------------
> db.emp.find()
{ "_id" : 100, "name" : "king", "sal" : 5000 }
{ "_id" : 101, "name" : "miller", "sal" : 3000 }
{ "_id" : 102, "name" : "ramu", "sal" : 3000 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }


Update single field in a single document
--------------------------------------------------------
> db.emp.update({_id:100},{$set:{sal:9500}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find()
{ "_id" : 100, "name" : "king", "sal" : 9500 }
{ "_id" : 101, "name" : "miller", "sal" : 3000 }
{ "_id" : 102, "name" : "ramu", "sal" : 3000 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }


> db.emp.update({sal:3000},{$set:{sal:3500}})   (here sal=3000 two documents are there but first one updated so use multi:true)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find()
{ "_id" : 100, "name" : "king", "sal" : 9500 }
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 102, "name" : "ramu", "sal" : 3000 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }


> db.emp.update({sal:3000},{$set:{sal:3500}},{multi:true})  (here sal=300 two documents matched so both are updated)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

> db.emp.find()
{ "_id" : 100, "name" : "king", "sal" : 9500 }
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 102, "name" : "ramu", "sal" : 3500 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }

Update – Add a new field
-----------------------------------------------
> db.emp.update({_id:100},{$set:{loc:'hyderabad'}})              (here id=100 in this document loc field is not there so add otherwise updated)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find()
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 102, "name" : "ramu", "sal" : 3500 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }
{ "_id" : 100, "name" : "king", "sal" : 9500, "loc" : "hyderabad" }

Update multiple fields and add new fields
--------------------------------------------------
> db.emp.update({_id:102},{$set:{loc:'guntur',sal:4000,name:'kiran'}})    (in this id=102 document loc field  is not there so add, remaing fields are there so  updated)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.emp.find()
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 103, "name" : "gnr", "sal" : 6000 }
{ "_id" : 100, "name" : "king", "sal" : 9500, "loc" : "hyderabad" }
{ "_id" : 102, "name" : "kiran", "sal" : 4000, "loc" : "guntur" }


Update subdocument (Here filedname specified with " wife.name"="rani ")
--------------------------------------------------------------------------------------------
> db.emp.update({_id:103},{$set:{"lover.name":"divya","lover.age":23}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find()
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 100, "name" : "king", "sal" : 9500, "loc" : "hyderabad" }
{ "_id" : 102, "name" : "kiran", "sal" : 4000, "loc" : "guntur" }
{ "_id" : 103, "name" : "gnr", "sal" : 6000, "lover" : { "name" : "divya", "age" : 23 } }


Update-Remove a field (by using $unset)
-------------------------------------------------------------------------
> db.emp.update({_id:103},{$unset:{"lover.age":23}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find()
{ "_id" : 101, "name" : "miller", "sal" : 3500 }
{ "_id" : 100, "name" : "king", "sal" : 9500, "loc" : "hyderabad" }
{ "_id" : 102, "name" : "kiran", "sal" : 4000, "loc" : "guntur" }
{ "_id" : 103, "name" : "gnr", "sal" : 6000, "lover" : { "name" : "divya" } }


Update – Insert a new document if no match found
--------------------------------------------------------------------------------------------------------------
> db.emp.update({_id:104},{$set:{name:"venkat",sal:2500}})    //here _id=104 document is not there ,so no changes 
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

>db.emp.update({_id:104},{$set:{name:"venkat",sal:2500}},{upsert:true})     //here _id=104 document is not there  so insert these documnet
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 104 })

> db.emp.find({_id:104})
{ "_id" : 104, "name" : "venkat", "sal" : 2500 }


Update multiple documents
--------------------------------------------------------------------------------------------------------------
> db.emp.update({_id:{$lt:102}},{$inc:{sal:1000}})   //here id<102   //only one document salary incremnted  , to increment sal all documnets like id<102 then  specifylast argumnet multi:true
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })


> db.emp.update({_id:{$lt:102}},{$inc:{sal:1000}},{multi:true}) 
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })


 Update documnet existing field value and also incrmrent sum  value to the existing value
------------------------------------------------------------------------------------------------------------------
> db.emp.update({_id:103},{$set:{name:"gnrc",age:24},$inc:{sal:250}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find({_id:103})
{ "_id" : 103, "name" : "gnrc", "sal" : 6250, "lover" : { "name" : "divya", "age" : 23 }, "age" : 24 }



> db.emp.update({_id:103},{$set:{name:"gnr",age:25},$inc:{sal:250,comm:100},})  //here comm fiels is not there so first time add comm filed with value 100
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find({_id:103})
{ "_id" : 103, "name" : "gnr", "sal" : 6500, "lover" : { "name" : "divya", "age" : 23 }, "age" : 25, "comm" : 100 }


NOTE:at a time same field only one time update is possible
-------------------------------------------------------------------------------------
> db.emp.update({_id:103},{$set:{name:"gnr"},$inc:{sal:250,comm:100,age:10},$rename:{age:"sage"}})   //in this Query age to times so error

> db.emp.update({_id:103},{$set:{name:"gnr"},$inc:{sal:250,comm:100},$rename:{age:"sage"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.emp.find({_id:103})
{ "_id" : 103, "name" : "gnr", "sal" : 7500, "lover" : { "name" : "divya", "age" : 23 }, "comm" : 100, "sage" : 25 }


Comments

Post a Comment