Friday, 18 March 2016

Working with mongodb

start service

>     Sudo service mongod start

>    mongo


>  Sudo service mongod stop

>  Sudo service mongod restart

> exit

> show dbs

---------------------------------------------------------------

Create Database


creating database
use DATABASE_NAME

>use mydb
switched to db mydb

To check your currently selected database
>db
mydb
 to check your databases list
>show dbs
local     0.78125GB
test      0.23012GB

Your created database (mydb) is not present in list. To display database you need to insert atleast one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB

                    

-------------------------------------------------------------
                       

                     dropDatabase()


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 }
>
Now check list of databases
>show dbs
local      0.78125GB
test       0.23012GB
>



-------------------------------------------------------------------------

                 createCollection()


db.createCollection(name, options)

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
>show collections
mycollection
system.indexes

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }
>
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
--------------------------------------------------------------------------

Drop Collection


Basic syntax of drop()
db.COLLECTION_NAME.drop()
First, check the available collections into your database mydb

>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection
>db.mycollection.drop()
true
>
Again check the list of collections into database

>show collections
mycol
system.indexes
tutorialspoint
>
-----------------------------------------------------------------------------------


Insert Document


The insert() Method


>db.COLLECTION_NAME.insert(document)



>db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})
To insert multiple documents in single query,


>db.post.insert([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'tutorials point',
      url: 'http://www.tutorialspoint.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: 'NoSQL database doesn't have tables',
      by: 'tutorials point',
      url: 'http://www.tutorialspoint.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
])

---------------------------------------------------------------------------------------

Query Document


The find() Method


>db.COLLECTION_NAME.find()


The pretty() Method


>db.mycol.find().pretty()


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


AND in MongoDB


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


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


OR in MongoDB



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


>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>


------------------------------------------------------------------------------------


Update Document



MongoDB's update() and save() methods are used to update document into a collection.

>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Consider the mycol collectioin
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

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'}})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>


By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})

MongoDB Save() Method



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

The save() method replaces the existing document with the new document passed in save() method


Following example will replace the document with the _id '5983548781331adf45ec7'

>db.mycol.save(
   {
      "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic",
         "by":"Tutorials Point"
   }
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
   "by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>



------------------------------------------------------------------------------------- -------
  

Import Example Dataset

> Open terminal    .......   >             ctrl+alt+t

> save the record with     extension   (.json)

> change the directory to where the file is located..

mongoimport --db test --collection restaurants --drop --file restaurant.json

>>>

then check the collections...by typing   


>mongo

> show dbs

>use db

>db.restaurant.find().pretty()
---------------------------------------------------------------------------------------



          Aggregation and Groups
**************************************************************************

> db.users.findOne()


{
"_id" : ObjectId("56f6281c2d88abaee449eef3"),
"isActive" : false,
"balance" : "$3,960.64",
"age" : 30,
"eyeColor" : "blue",
"name" : "Dawn Keith",
"gender" : "female",
"company" : "COSMOSIS",
"email" : "dawnkeith@cosmosis.com",
"phone" : "+1 (839) 437-3421",
"address" : "392 Clifford Place, Fontanelle, Arizona, 2687"

}

*******************************************************************************

1)

> db.users.aggregate({
    $group : {
     _id   : "gender" ,
     total : {  $sum : 1 }
   }
})


O/p::::


{ "_id" : "gender", "total" : 35 }



Note:  here  _id : "gender"



2)
> db.users.aggregate({
    $group : {
     _id   : "$gender" ,
     total : {  $sum : 1 }
   }
})

O/p::::


{ "_id" : "female", "total" : 15 }
{ "_id" : "male", "total" : 20 }

Note:  here  _id : "$gender"

**************************************************************************************************************
 Average 


> db.users.aggregate({
 $group:{
   _id : "$gender",
   avgAge: {$avg :"$age"}
 }
})

O/p::::

{ "_id" : "female", "avgAge" : 30.8 }

{ "_id" : "male", "avgAge" : 32.5 }



************************************************************************************************************
Max

> db.users.aggregate({
 $group :{
    _id : "$gender",
    richest : {$max : "$balance"}
 }
})


O/p::

{ "_id" : "female", "richest" : "$3,960.64" }
{ "_id" : "male", "richest" : "$3,818.97" }


****************************************************************************************************



Example :  db                 :  amazon
                 Collections     : Orders


> db
amazon


> show collections
orders

> db.orders.find().pretty()

{
"_id" : ObjectId("56f65a212d88abaee449ef16"),
"cust_id" : "A123",
"amount" : 500,
"status" : "A"
}
{
"_id" : ObjectId("56f65ad52d88abaee449ef17"),
"cust_id" : "A123",
"amount" : 250,
"status" : "A"
}
{
"_id" : ObjectId("56f65ad52d88abaee449ef18"),
"cust_id" : "B212",
"amount" : 200,
"status" : "A"
}
{
"_id" : ObjectId("56f65ad52d88abaee449ef19"),
"cust_id" : "A123",
"amount" : 300,
"status" : "D"

}

**************************************************************************************************
example:


1)

> db.orders.aggregate([
{$match:{status:"A"}},
{$group:{ _id:"cust_id",total:{$sum:"$amount"}}}
])


O/p:

{ "_id" : "cust_id", "total" : 950 }

2)

> db.orders.aggregate([

{$match:{status:"A"}},
{$group:{ _id:"$cust_id",total:{$sum:"$amount"}}}
])
O/p:::

{ "_id" : "A123", "total" : 750 }

{ "_id" : "B212", "total" : 200 }

******************************************************************************************************


     Single Purpose Aggregation Operations


1)    db.collection.count() 
2) db.collection.group()
3) db.collection.distinct()





*****************************************************************************************************

Count all Documents in a Collection

To count the number of all documents in the orders collection, use the following operation:
db.orders.count()
This operation is equivalent to the following:
db.orders.find().count()

********************************************************************************************************

Count all Documents that Match a Query

Count the number of the documents in the orders collection with the field ord_dt greater than newDate('01/01/2012'):
db.orders.count( { ord_dt: { $gt: new Date('01/01/2012') } } )
The query is equivalent to the following:
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

-------------------------------------------------------------------------------------------------------------------



example:

> db.users.count( {age : {$gt:35}})
12



> db.users.count({balance:{$gt:"$2000"}})
11


**************************************************************************************************************


                          Update Specific Fields




For example, given a books collection with the following document:
{
  _id: 1,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
  reorder: false
}
The following operation uses:
  • the $inc operator to increment the stock field; and
  • the $set operator to replace the value of the item field, the publisher field in the info embedded document, the tags field, and the second element in the ratings array.
db.books.update(
   { _id: 1 },
   {
     $inc: { stock: 5 },
     $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
     }
   }
)
The updated document is the following:

{
  "_id" : 1,
  "item" : "ABC123",
  "stock" : 5,
  "info" : { "publisher" : "2222", "pages" : 430 },
  "tags" : [ "software" ],
  "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
  "reorder" : false
}


example:

>db.books.find().pretty()


{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : {
"publisher" : "1111",
"pages" : 430
},
"tags" : [
"technology",
"computer"
],
"ratings" : [
{
"by" : "ijk",
"rating" : 4
},
{
"by" : "lmn",
"rating" : 5
}
],
"reorder" : false
}
{
"_id" : 2,
"item" : "fiction",
"stock" : 5,
"info" : {
"publisher" : "mongo",
"pages" : 99
},
"tags" : [
"tech",
"soft"
],
"ratings" : [
{
"by" : "abc",
"rating" : 3
},
{
"by" : "def",
"rating" : 4
}
],
"reorder" : true

}

-----------------------------------------------------------------------------------------------------------------

> db.books.update(
{_id: 2},
$inc : {stock: 99},
$set : {
      "ratings.0": { by : "sri", rating : 5  }

}
 }
)


--------------------------------------------------------------------------------------------------------------------










No comments:

Post a Comment