Saturday, February 4, 2017

MongoDB Basic Commands

To start the server:
--------------------
Go to -> command promt -> set the path till bin
ex:
C:\mongodb-win32-i386-2.6.4\bin
then -> mongod --dbpath C:\mongodb-win32-i386-2.6.4\bin
the server will start running

create db & select a db
-----------------------
use tommy

create collections
-------------------
use tommy - select the db
db.createCollection("employees")

create collections and insert the data
---------------------------------------
db.employees.insert({"id":111,"name":"tom"})

view the list of dbs
---------------------
show dbs

view the list of collections(tables)
------------------------------------
show collections

view the records in the collections
-----------------------------------
db.employees.find()

Delete a collection
-------------------
db.employees.drop() - to delete the collection
db.employees.remove() - remove all the records from the collection

Delete a speciic doc from the collection
-----------------------------------------
>db.employees.remove({name:"tom"})
>db.employees.remove({name:"tom"},1) - will delete oly one record

to view the current db
-----------------------
db

delete a db
-------------
use tommy - select a db
db.dropDatabase()

note
-----
>in mongodb you dont need to create collections.
>it creates collections automatically, when you insert some documents

insert multiple documents in a single query
------------------------------------------
db.employees.insert([{ },{ }])

to display the results in a formatted way
-----------------------------------------
db.employees.find().pretty()

update
---------
db.employees.update({name:'tomfree'},{$set:{name:'tomm'}})
>db.employee.update({id:111},{$set:{desig:'sr manager'}})
>db.employee.update({"_id" : ObjectId("529589614eff477245718bdc")},{$set:{email:'cristina@gmail.com'}})
- to add an extra field

to update multiple docs
------------------------
db.employees.update({name:'tomfree'},{$set:{name:'tomm'}},{multi:true})

to update multiple docs - with options
--------------------------------------
db.your_collection.update({},{$set : {"new_field":1}},false,true)

db.your_collection.update({},{$set : {"new_field":1}},{upsert:false,multi:true})

Note:
-----

-> In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

-> This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

to get the sum of the single field:
-----------------------------------
db.Gits_OpenClose.aggregate({$match:{"Year": 2014,"Month": 1}},{$group:{_id: null,total:{$sum:"$Opened"}}})

to update the existing collections with other datas
-----------------------------------------------------
db.employees.save({_id: ObjectId("52945e82e2c023a457cf152e"),name:'tom',id:1111})
>this s by using object_id

to find a specific column
----------------------------
db.employees.find({},{oth:1,_id:0})
>oth - column name
>1 - used to show the specific field
>0 - not to show
>_id:0 - to hide the object id

to limit the records:
----------------------
db.employees.find({},{oth:1,_id:0}).limit(2)

skip method:
------------
db.employees.find({},{oth:1,_id:0}).limit(1).skip(1)
>the default value of skip method is 0.

Sorting:
--------
db.employees.find({},{oth:1,_id:0}).sort({'oth':1})
>1 - ascending
>-1 - descending
db.data.find({},{'Org From Date':''}).sort({'Org From Date':-1}).limit(50)

update:
-------
>db.Employee.update({"_id" : ObjectId("529489e1f2e76698bd1c1616")}, {$set: {"Skill.Sports": "Cricket"}});
>db.Employee.update({_id: ObjectId("529489e1f2e76698bd1c1616")}, {$set: {'Skills.tech':['nosql','java']}});

where conditions
-----------------
>db.employee.find({gender:'f'}) - where gender=f
>db.employee.find({salary:{$gt:50000}}) - where salary>50000
>db.employee.find({salary:{$gt:50000}},{name:1,desig:1,_id:0}) - select name,desig from employee where salary>50000

Indexing
----------
db.employee.ensureIndex({'id':1})
>1 - creating index in ascending order
>2 - creating index in descending order

Aggrigation
------------
db.employee.aggregate([{$group : {_id : "$id", num_tutorial : {$sum : 1}}}])

aggrigation - where
--------------------
db.employee.aggregate([{$match:{salary:{$gt:50000}}},{$group : {_id : "$gender", num_tutorial : {$sum : 1}}}])

Aggre - operations
------------------
count - db.employee.count() - table total count
count - db.employee.count({city:'blore'}) - count of city which is blore
distinct - db.employee.distinct('city')
db.test.count({sports:'football,hockey'},{name:'',sports:''})

in
---
db.case_tbl.find( { empid: { $in: [ 96761, 95939 ] } } )
db.employee.find({id:{$in:[111,222,333]}},{name:'',desig:'',_id:0})

skip() - if wanna skip first 2 docs
-----------------------------------
db.employee.find().skip(2)

total sum:
-----------
db.procount.aggregate({$group:{_id:null,total:{$sum:'$ProCount'}}})

important
----------
db.Employee.find({ "Contact.ZipCode" : "600071"},{"Contact.Address":1})

aggregate:
----------
db.employee.aggregate({$group:{_id:'$city',total_count:{$sum:1},max_salary:{$max:'$salary'},
min_salary:{$min:'$salary'},avg_salary:{$avg:'$salary'}}})

multiple group:
-----------------
db.employee.aggregate([{$group:{_id:{city:'$city',Design:'$desig'},count:{$sum:1}}}])

var a=db.employee.aggregate([{$group:{_id:{city:'$city',design:'$desig'},count:{$sum:1}}}])
printjson(a)

to insert multiple records:
----------------------------
for(var i=1;i<=10;i++)db.test.insert({id:111,name:'tom',desig:'ase',salary:5000})

import csv to mongodb
----------------------
mongoimport --host localhost --db test --collection data --type csv --file Emp_Data.csv --headerline

distinct count
---------------
db.data.distinct('Emp NO').length

OR:
---
db.emp1.aggregate(
  {$match:{$or:[{"DOE.YEAR":null},{"DOE.YEAR":2013}],"DOJ.YEAR":{$lte : 2013}}},
  {$group:{_id:{},
   count:{ $sum:1}}})

some operators:
---------------
$cmp - compare
$eq - equal
$gt - greater than
$gte - greater than or eequal to
$lt - less than
$lte - less than or equal to
$ne - not equal to

4 comments:

  1. Excellent Blog! I would Thanks for sharing this wonderful content.its very useful to us.I gained many unknown information, the way you have clearly explained is really fantastic.This is incredible,I feel really happy to have seen your webpage
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  2. You have posted an informative post. Looking forward to read more.
    Best Web Design Services

    ReplyDelete
  3. Its really helpful for the users of this site. I am also searching about these type of sites now a days.
    MongoDB Training in Bangalore

    ReplyDelete