Friday, January 20, 2017

NOSQL -MongoDB

Introduction





Setup Mongo


Download & Install Mongo from- MongoDB site

Now you need a folder to store the data. So, Create one and Setup mongo.

Run MongoDB command in console-

mongod --directoryperdb --dbpath <folder path> --logpath <file path> --logappend --rest 

Mongo commands


Great, you are ready to do DB functionalities. For this, you have to run following command in the console. 

mongo

That's it. It will open a shell for executing mongo commands.

Show list of DBs-
>show DBS

Create/Use the DB-
>use local

See selected DB-
>db

Create user for db-
>db.createUser({user:"test",pwd:"1234",roles: ["readWrite","dbAdmin"]});

Create a collection in DB-
>db.createCollection('employee');

Show all collections in DB-
>show collections

Insert document in a collection-
>db.employee.insert({first_name:"sudhir", last_name:"ghosh"});

Fetch the documents-
>db.employee.find();

Insert multiple documents-
>db.employee.insert([{first_name:"sakti", last_name:"ghosh"},{first_name:"subha", last_name:"ghosh", gender:"M"}]);

Get Collection-
>db.employee.find().pretty();

Update commands -
>db.employee.update({first_name:"sakti"},{first_name:"sakti", last_name:"ghosh",gender:"M"});

>db.employee.update({first_name:"sudhir",{$set:{age: 40}});

>db.employee.update({first_name:"sudhir",{$inc:{age:5}});

>db.employee.update({first_name:"sudhir",{$unset:{age}});

>db.employee.update({first_name:"rnga"},{first_name:"ranga", last_name:"ghosh"},{upsert:true});

>db.employee.update({first_name:"rnga"},{$rename:{"gender":"m"}});

Remove commands -
>db.employee.remove({first_name:"rnga"});

>db.employee.remove({first_name:"rnga"}, {justOne:true});

Find Commands -
>db.employee.find({first_name:"sudhir"});

>db.employee.find({$or:[{first_name:"sakti"},{first_name:"sudhir"}]});

>db.employee.find({age:{$lt:40}}); //$gt/$gte/$lte

>db.employee.find({"address.city":"kol"});//json path

>db.employee.find().sort({last_name:1});//asc/desc (-1)

>db.employee.find().count();

>db.employee.find().limit(4);

>db.employee.find({deot:{$in:['software','testing']}});

>db.employee.find().forEach(function(doc){
print('name:'+ oc.first_name)});



Further study - https://docs.mongodb.com/manual/
Post a Comment