Tuesday, July 26, 2016

MongoDB – CRUD (Create, Read, Update, Delete)




MongoDB – CRUD
 (Create, Read, Update, Delete) 


Before moving further with CRUD operation in mongodb.You can refer the below table of comparison of MongoDb vs Any relational database (Oracle Mysql,DB2 etc.)


So as you can see in above figure.in Mongodb Sql table are referred as Collections.

1.Create


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 which is optional.

Examples:
Basic syntax of createCollection() method without options is as follows

use test
switched to db test
db.createCollection("mycollection")
{ "ok" : 1 }
You can check the created collection by using the command show collections

show collections
mycollection
system.indexes

In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document(Row in sql).

db.tutorialspoint.insert({"name" : "tutorialspoint"})

show collections
mycollection
system.indexes
tutorialspoint

2.Read

findOne 
find

Syntax:
• db.collection_name.findOne( <condition>, <fileds to fetch> );
• db.collection_name.find( <condition>, <fileds to fetch> );

Example:
> db.test.insert({"name":"Rahul"});
WriteResult({ "nInserted" : 1 })
> db.test.insert({"name":"Rahul_2"});
 WriteResult({ "nInserted" : 1 })
SQL   : select * from (Select * from test where name ="Rahul")  where rownum=1;

Mongo : db.test.findOne({"name":"Rahul"});
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }

SQL : Select * from test where name ="Rahul";
Mongo: db.test.find({"name":"Rahul"});
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }

SQL : Select * from test
Mongo:  db.test.find();
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }
{ "_id" : ObjectId("57386739212b0a31faedc82c"), "name" : "Rahul_2" }


Incase we need specific field from collections i.e fetch selected columns of table we can below commands.
 db.inventory.insert(
    {
    item: "ABC1",
     details: {
         model: "14Q3",
         manufacturer: "XYZ Company"
      },
    stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
     category: "clothing"
   }
)
WriteResult({ "nInserted" : 1 })

SQL : Select item from inventory;
Mongo : db.inventory.find({},{item:1});
{ "_id" : ObjectId("57386b1befcf19a06c49f0a0"), "item" : "ABC1" }
Incase you want to remove _id field we can use below command.

Mongo: db.inventory.find({},{item:1, _id:0});
Result : { "item" : "ABC1" }







Sunday, May 15, 2016


Capped collections 


Capped collections are fixed-size circular collections that follow the insertion order to support high performance for create, read and delete operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands.

Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the order of the disk storage, it ensures that the document size does not increase the size allocated on disk. Capped collections are best for storing log information, cache data or any other high volume data.

db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }

If you want to check whether a collection is capped or not, use the following isCapped command:

db.cappedLogCollection.isCapped()

If there is an existing collection which you are planning to convert to capped, you can do it with the following code:

db.runCommand({"convertToCapped":"posts",size:10000})

This code would convert our existing collection posts to a capped collection.

Querying Capped Collection:

By default a find query on a capped collection will display results in insertion order. But if you want the documents to be retrieved in reverse order, use the sort command as shown in the following code:

db.cappedLogCollection.find().sort({$natural:-1})

There are few other important points regarding capped collections worth knowing:

We cannot delete documents from a capped collection.There are no default indexes present in a capped collection, not even on _id field.While inserting a new document, MongoDB does not have to actually look for a place to accommodate new document on the disk. It can blindly insert the new document at the tail of the collection. This makes insert operations in capped collections very fast.
Similarly, while reading documents MongoDB has just to return documents in the same order as present on disk. This makes the read operation very fast.

Mongo Server installation with Config file(BackGround run)


In this tutorial, I will show you how to install MongoDB on Windows.


  1. MongoDB 2.2.3
  2. Windows 7

1. Download MongoDB

Download MongoDB from official MongoDB website. Choose Windows 32 bits or 64 bits. Unzip, extracts to your prefer location, for example : d:\mongodb\.

2. Configuration File
Create a MongoDB config file, it’s just a text file, for example : d:\mongodb\mongo.config

Enter the below entries

dbpath=D:\mongodb\data

##all output go here
logpath=D:\mongodb\log\mongo.log

##Run mongo server in background
fork=true

NOTE:
MongoDB need a folder (data directory) to store its data. By default, it will store in “C:\data\db“,
create this folder manually. MongoDB won’t create it for you. You can also specify an alternate data directory with --dbpathoption.


3.Run MongoDB server

Use mongod.exe --config d:\mongodb\mongo.config to start MongoDB server.

For eg :-
d:\mongodb\bin>mongod --config D:\mongodb\mongo.config
all output going to: D:\mongodb\log\mongo.log

You Should get message something like below
about to fork child process, waiting until server is ready for connections.
forked process: <PID for mongo server>

4.Connect to MongoDB Server (by running client)

Above command on step 3 has started mongo server and it ready to receive connection from client.

Open new terminal and direct to bin folder of mongodb which was installed and run below command.

d:\mongodb\bin>mongo
 MongoDB shell version: 2.2.3
  connecting to: test
> //mongodb shell

on Server terminal you can see below message that it has received one connection.

2016-05-15T16:43:12.679+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:62866 #1 (1 connection now open)