Sunday, 23 June 2019

Update Priority and votes options in Replica Set config

To update priority and votes in rc.conf():


Important notes:

  -  Re-configuring priority can force the current primary to step down, which causes an election. The rs.reconfig() shell method can force the current primary to step down. When the primary steps down, the mongod closes all client connections and it takes 10-20 seconds to elect new primary. So make priority setting changes during scheduled maintenance periods only.

  -  Avoid re-configuring replica sets that contain members of different MongoDB versions as validation rules may differ across MongoDB versions.

 Note: MongoDB version 4.0.9.

Steps:

Check the priority and votes of all replica members:

rs0:PRIMARY> rs.conf()
{
"_id" : "rs0",
"version" : 3,
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"members" : [
{
"_id" : 0,
"host" : "localhost:27000",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "localhost:27001",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "localhost:27002",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 0,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 0
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {

},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5d0e133f74cae82235a32ff7")
}
}

In the above output, member[2] has priority and votes as 0. So it can' not participate in election and it has no option to become as primary.

Use 'cfg' variable to assign replica set configuration (You can use any name as variable).

rs0:PRIMARY> cfg = rs.conf()
{
"_id" : "rs0",
"version" : 5,
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"members" : [
{
"_id" : 0,
"host" : "localhost:27000",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "localhost:27001",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "localhost:27002",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 0,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 0
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {

},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5d0e133f74cae82235a32ff7")
}
}

Now change the priority and votes using below commands:

rs0:PRIMARY> cfg.members[2].priority = 1;
1
rs0:PRIMARY> cfg.members[2].votes = 1;
1

Reconfig the configuration to apply changes:

rs0:PRIMARY> rs.reconfig(cfg)
{
"ok" : 1,
"operationTime" : Timestamp(1561205134, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1561205134, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}

Now check updated configuration values:

rs0:PRIMARY> rs.conf()
{
"_id" : "rs0",
"version" : 3,
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"members" : [
{
"_id" : 0,
"host" : "localhost:27000",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "localhost:27001",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "localhost:27002",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {

},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5d0e133f74cae82235a32ff7")
}
}

Note:
Configuration changes should be done in Primary only, you can not do in secondaries.

rs0:SECONDARY> rs.reconfig(cfg)
{
"operationTime" : Timestamp(1561205414, 1),
"ok" : 0,
"errmsg" : "replSetReconfig should only be run on PRIMARY, but my state is SECONDARY; use the \"force\" argument to override",
"code" : 10107,
"codeName" : "NotMaster",
"$clusterTime" : {
"clusterTime" : Timestamp(1561205414, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}


Note: Base information from MongoDB docs.


                                                                                                                   -- Thiru //

Priority and Votes in Replica Set config in MongoDB


For High Availability, In Replica set, priority and votes fields are very important and play key role while electing new primary in case of any issue with current primary.

Priority:


Based on value assigned to priority field, it has priority to participate in election and to become as a primary. By default all secondary members are eligible to become as primary though election process.

To modify priorities, you can update array of members in replica set configuration. The array index begins with 0.

General form like, members[n].priority = value.

       Ex:    members[0].priority = 0.5
members[1].priority = 2.

In the above example, member 1 has high priority to become as primary, member 0 has low priority.

We can give any number between 0 and 1000 as a value to priority field of members. The default value for the priority field is 1.

To block a member from becoming as a primary, change the priority value of that member to 0.

         Ex: members[2].priority = 0.

Votes and voting:


A replica set can have up to 50 members, but voting members should be 7 only, remaining nodes we can add as non-voting members. These non-voting members can have data and will allow read connections from client application, but don't participate and vote in elections.

For non-voting members, Priority and votes value should be equal to 0.
Members with priority greater than 0 cannot have 0 votes. But members with votes equal to 1, can have priority as 0, like Arbiter node.

Arbiter node has priority value equal to 0 as it should not become as primary as it doesn't hold any data and it has votes equal to 1 as it should participate in election to elect new primary. If your replica set has even number of nodes, you can add an arbiter node to avoid tie during elections for new primary.


We can check priority and votes with rs.conf() by connecting to database server.

rs0:PRIMARY> rs.conf()
{
"_id" : "rs0",
"version" : 3,
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"members" : [
{
"_id" : 0,
"host" : "localhost:27000",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "localhost:27001",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "localhost:27002",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {

},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {

},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5d0e133f74cae82235a32ff7")
}
}

Note: Base information from MongoDB docs.

Updating values of priority and votes in replica set configuration, will share in next post .. :)


                                                                                                                       -- Thiru //

Thursday, 11 January 2018

Install MongoDB 3.6 in Windows (Using .msi Installer)

Installation:


First check your OS architecture using:

wmic os get osarchitecture

          If it is 64-bit architecture, get latest 3.6 community installer from MongoDB official link

Note:From MongoDB 3.4, MongoDB no longer supports 32-bit x86 platforms.
         For MongoDB 3.6 community Edition, requires Windows Server 2008 R2, Windows 7, or later.
         
          If you install through .msi installer, it includes all other software dependencies and will automatically upgrade any older version of MongoDB installed in that machine.



      
Read License agreement and accept the license to proceed. Then press next.



 Here, we will get 2 options to choose mongo installation.

    Complete: It will install complete package in default paths.
    Custom:  We can select required features and path to install.



            If you select ‘custom’, window will be like below:


Note: Here you can select which features need to install and can specify location manually where we need to install.

 If you select ‘complete’ set up, installation will happen in default path with all available features.

           If you want compass, select ‘Install MongoDB Compass’. Press next.


Now it is ready to install mongoDB. Press on Install.




      Press on Finish to complete installation.


Start and connect to mongoDB Server:


Note: Default Installation path : c:\Program Files\MongoDB\Server\3.6\bin
          Default data Dir  path : c:\data\db.

To start mongod process, we need to create data directory to store all data. 

md c:\data\db

          Note: You can create data directory in different path also. You have to specify that path in dbpath while starting mongod process.
           
         Start mongod process by specifying above dbpath.

c:\Program Files\MongoDB\Server\3.6\bin>mongod.exe --dbpath c:\data\db

Note: If you got log message like ‘waiting for connections on port 27017’ on command prompt after mongod process start, then process is started and ready to connect to mongo server.


Now open another command prompt and connect to mongo server using:

c:\Program Files\MongoDB\Server\3.6\bin>mongo.exe

        Now you are inside DB, by default it will connect to ‘test’ DB.

     Now you can run all DB related commands.

                                                                                                                                        -- Thiru //

Sunday, 17 December 2017

Part:2 CRUD Operations in MongoDB

Continuation to part-1 about CRUD operations.

UPDATE:


This operation modifies an existing documents in a collection. Based on condition/criteria provided in query, it updates one or more documents in a collection.

We have different methods to update documents in a collection.

1. It modifies an existing document(s) as per condition. Either update/replace a single document or update all documents that match the condition.

     Syntax:

    db.<<collection_name>>.update({<<query>>},{{ <<update>>},{<< options>>})

     Here,
   Query:  Condition/criteria to select documents for update. Means which document to update

   Update:  what to update in the document which we got with matching criteria.

   Options:
upsert:  true, if no document returns with matching criteria, it inserts document. By default this value is false.
Multi: true, update method will update all documents that matches the condition.

Note: By default, update() method will update one document only. To update all documents that match the query criteria/condition, use multi: true in options.

Ex:

           > db.sample.find()
            { "_id" : 1, "no" : 12, "name" : "abc", "item" : "aaa" }
            { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "abc", "item" : "aaa" }
            { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "abc", "item" : "aaa" }

          >  db.sample.update({no: 12}, {$set:{name:"asdf"}})
             WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

          > db.sample.find()
           { "_id" : 1, "no" : 12, "name" : "asdf", "item" : "aaa" }
           { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "abc", "item" : "aaa" }
           { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "abc", "item" : "aaa" }

         > db.sample.update({no: 12}, {$set:{name:"asdf"}},{multi: true})
           WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 2 })

         > db.sample.find()
          { "_id" : 1, "no" : 12, "name" : "asdf", "item" : "aaa" }
          { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "asdf", "item" : "aaa" }
          { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "asdf", "item" : "aaa" }

2. This method updates a single document in the collection that matches the criteria. If condition returns more than one document, it updates first document only.

     Syntax:

    db.<<collection_name>>.updateOne({<<filter>>},{<< update>>},{<< options>>})

       Ex:

       > db.sample.find()
        { "_id" : 1, "no" : 12, "name" : "asdf", "item" : "aaa" }
        { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "asdf", "item" : "aaa" }
        { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "asdf", "item" : "aaa" }

       > db.sample.updateOne({no:12},{$set:{name:"zzz", item:"abc"}})
        { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

       > db.sample.find()
        { "_id" : 1, "no" : 12, "name" : "zzz", "item" : "abc" }
        { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "asdf", "item" : "aaa" }
        { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "asdf", "item" : "aaa" }

3. This method updates all matching documents in a collection based on condition.

     Syntax:

            db.<<collection_name>>.updateMany({<<filter>>},{<< update>>}, {<<options>>})

        Ex:

      > db.sample.find()
       { "_id" : 1, "no" : 12, "name" : "zzz", "item" : "abc" }
       { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "asdf", "item" : "aaa" }
       { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "asdf", "item" : "aaa" }

     > db.sample.updateMany({no:12},{$set:{name:"raja", item:"any"}})
      { "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

     > db.sample.find()
      { "_id" : 1, "no" : 12, "name" : "raja", "item" : "any" }
      { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
      { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }

4. This method replaces a single document in a collection that matches a condition. If condition returns more than one document, it replaces first document.

     Syntax:

            db.<<collection_name>>.replaceOne({<<filter>>}, {<<replacement>>},{<< options>>})

Note: It replaces the entire content of a document except ‘ _id’ field, in the second argument, give entirely new document to replace.

      Ex:

     > db.sample.find()
      { "_id" : 1, "no" : 12, "name" : "raja", "item" : "any" }
      { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
      { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }

     > db.sample.replaceOne({no:12},{name: "ranga"})
      { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

      > db.sample.find()
       { "_id" : 1, "name" : "ranga" }
       { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
       { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }

DELETE:


This operation is used to remove documents from a collection. We can remove all documents or documents based on condition from a collection.

     Syntax:

           db.<<collection_name>>.remove()

OR

           db.collection.remove({ <<query>>}, <justOne>)

       Here,
             Query: Specifies to delete documents based on condition.
             justOne:  set to true, to delete only one document.

        Ex:

       > db.sample.find()
        { "_id" : 1, "name" : "ranga" }
        { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
        { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }
        { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
        { "_id" : ObjectId("5a355a053f46e9bcf9838478"), "no" : 4, "name" : "eee", "pin" : 12345 }
        { "_id" : ObjectId("5a355a053f46e9bcf9838479"), "no" : 5, "name" : "fff" }

       > db.sample.remove({no: 4})
         WriteResult({ "nRemoved" : 1 })

       > db.sample.find()
        { "_id" : 1, "name" : "ranga" }
        { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
        { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }
        { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
        { "_id" : ObjectId("5a355a053f46e9bcf9838479"), "no" : 5, "name" : "fff" }

       > db.sample.remove({}, true)
         WriteResult({ "nRemoved" : 1 })

       > db.sample.find()
         { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "raja", "item" : "any" }
         { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }
         { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
         { "_id" : ObjectId("5a355a053f46e9bcf9838479"), "no" : 5, "name" : "fff" }

      > db.sample.remove({no: 12}, true)
        WriteResult({ "nRemoved" : 1 })

      > db.sample.find()
       { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "raja", "item" : "any" }
       { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
       { "_id" : ObjectId("5a355a053f46e9bcf9838479"), "no" : 5, "name" : "fff" }

     > db.sample.remove({})
       WriteResult({ "nRemoved" : 3 })


2.  This method removes a single document from a collection. It deletes first document if the given condition returns multiple documents.

Syntax:

db.<<collection_name>>.deleteOne()
Ex:

       > db.sample.find()
        { "_id" : ObjectId("5a365eac47f5367ba14a1651"), "no" : 1, "name" : "aaa" }
        { "_id" : ObjectId("5a365ebe47f5367ba14a1652"), "no" : 12, "name" : "bbb", "item" : "asd" }
        { "_id" : ObjectId("5a365ed247f5367ba14a1653"), "no" : 13, "name" : "ccc", "item" : "sdf" }
        { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }

      > db.sample.deleteOne({no:13})
       { "acknowledged" : true, "deletedCount" : 1 }

      > db.sample.find()
       { "_id" : ObjectId("5a365eac47f5367ba14a1651"), "no" : 1, "name" : "aaa" }
       { "_id" : ObjectId("5a365ebe47f5367ba14a1652"), "no" : 12, "name" : "bbb", "item" : "asd" }
       { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }

     > db.sample.deleteOne({no:{$lt:12}})
     { "acknowledged" : true, "deletedCount" : 1 }

     > db.sample.find()
      { "_id" : ObjectId("5a365ebe47f5367ba14a1652"), "no" : 12, "name" : "bbb", "item" : "asd" }
      { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }

      > db.sample.deleteOne({no:{$lt:15}})
       { "acknowledged" : true, "deletedCount" : 1 }

      > db.sample.find()
       { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }

3. This method will remove multiple documents that satisfies the given condition.

     Syntax:

db.<<collection_name>>.deleteMany()

      Ex:

      > db.sample.find()
       { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }
       { "_id" : ObjectId("5a3660f647f5367ba14a1655"), "no" : 12, "name" : "bbb", "item" : "asd" }
       { "_id" : ObjectId("5a3660fc47f5367ba14a1656"), "no" : 1, "name" : "aaa" }
       { "_id" : ObjectId("5a36610447f5367ba14a1657"), "no" : 12, "name" : "bbb", "item" : "asd" }

      > db.sample.deleteMany({no: 12})
       { "acknowledged" : true, "deletedCount" : 2 }

       > db.sample.find()
       { "_id" : ObjectId("5a365edf47f5367ba14a1654"), "no" : 13, "name" : "ccc", "item" : "sdf" }
       { "_id" : ObjectId("5a3660fc47f5367ba14a1656"), "no" : 1, "name" : "aaa" }

Note: Its mandatory to provide criteria/condition in deleteOne() and deleteMany() methods.

                                                                                                                             -- Thiru //

Part:1 CRUD Operations in MongoDB

Here, I am trying to explain CRUD operations with examples for better understanding.

So I am posting this in 2 parts. 

Part: 1: 


MongoDB has 4 basic operations Create/insert, Read, Update and Delete to add, read, modify and delete data in the shell.

CREATE:


This operation is used to add (create or insert) documents to a collection. 

We have different methods to insert documents into a collection. If collection doesn’t exist, insert will create collection with given name. 

1. Inserts single or multiple documents into a collection.

     Syntax: 

           db.<<collection_name>>.insert({<<document>>)

        Ex:
  
          > db.sample.insert({ no:1, name: "aaa"})
          > db.sample.insert([ 
           { no:3, name: "ddd", add: "abc" },
     { no:4, name: "eee", pin: 12345 },
     { no:5, name: "fff" }
           ])  

2. Inserts single document into a collection.

     Syntax:
 
           db.<<collection_name>>.insertOne({<<document>>})

Note: This method returns a document with:  acknowledged with Boolean value(True/false) and insertedId with objectId(_id).

         Ex: 

         > db.sample.insertOne({ no:12, name: "abc", item: "aaa" }

3. This method inserts multiple documents into a collection.

      Syntax:

            db.collection.insertMany() 

Note: This method returns a documents with: acknowledged with Boolean value(True/false) and an array of objectId (_id) for successful inserted documents

          Ex:

       > db.sample.insertMany([
        { no:3, name: "ddd", add: "abc" },
        { no:4, name: "eee", pin: 12345 },
        { no:5, name: "fff" }
         ])

Note:  Both methods InsertOne() and InsertMany() are not compatible with db.collection.explain()
We can also insert documents by using variable.

          Ex:
   
      > var a = { no:10, name: "abc", add: "aaa"}
      > db.sample.insert(a)

READ:


This operation is used to read/retrieve/find existing documents from collection.

We have 2 methods to find documents from collection.

1. It returns all documents or documents which satisfies the given condition.

     Syntax:
 
          db.<<collection_name>>.find({<<query>>},{<< projection>>})
      Here, 

        Query:  It specifies filter condition (Like where in RDBMS) using query operators to return documents based on condition. (Query filter or criteria).

        Projection:  It specifies which fields are required to return in result.  (1 or true to include field, 0 or false to exclude field).
Note: Both (query and projection) are optional. If not specified, find method returns all documents.
       Ex:

        > db.sample.find({})
         { "_id" : 1, "no" : 12, "name" : "abc", "item" : "aaa" }
         { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "abc", "item" : "aaa" }
         { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "abc", "item" : "aaa" }
         { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
         { "_id" : ObjectId("5a355a053f46e9bcf9838478"), "no" : 4, "name" : "eee", "pin" : 12345 }
         { "_id" : ObjectId("5a355a053f46e9bcf9838479"), "no" : 5, "name" : "fff" }

        > db.sample.find({no:12})
         { "_id" : 1, "no" : 12, "name" : "abc", "item" : "aaa" }
         { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "abc", "item" : "aaa" }
         { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "abc", "item" : "aaa" }

        > db.sample.find({no:{$lt:5}})
         { "_id" : ObjectId("5a355a053f46e9bcf9838477"), "no" : 3, "name" : "ddd", "add" : "abc" }
         { "_id" : ObjectId("5a355a053f46e9bcf9838478"), "no" : 4, "name" : "eee", "pin" : 12345 }

        > db.sample.find({no:12},{no:1, name:1})
         { "_id" : 1, "no" : 12, "name" : "abc" }
         { "_id" : ObjectId("5a3557c23f46e9bcf9838472"), "no" : 12, "name" : "abc" }
         { "_id" : ObjectId("5a3557c33f46e9bcf9838473"), "no" : 12, "name" : "abc" }

2. It returns one document from a collection. And returns first document (as per default order), if the given condition returns multiple documents.

     Syntax:

          db.<<collection_name>>.findOne({<<query>>}, {<<projection>>})

        Ex:
     > db.sample.findOne()
      { "_id" : 1, "no" : 12, "name" : "abc", "item" : "aaa" }

     > db.sample.findOne({no:12})
      { "_id" : 1, "no" : 12, "name" : "abc", "item" : "aaa" }

     > db.sample.findOne({no:12},{no:1, name: 1})
      { "_id" : 1, "no" : 12, "name" : "abc" }

I will post remaining 2 operations in second part.

                                                                                                                                      -- Thiru //                       

Wednesday, 29 November 2017

Introduction To MongoDB

Hi learners,

This is my first post on MongoDB. I hope this will help you to learn.

History:


Company was established as 10gen in 2007, a New York based Organization.In 2009, MongoDB was released as an open source database(Version 0.9). In 2013, Name has been changed to MongoDB Inc from 10gen.

Introduction:


MongoDB is an open-source document-oriented database. It is one of the most popular NoSQL databases and written in C++. It is a cross-platform database that supports Windows, Unix/Linux and Mac. It provides high performance, high availability, and easy scalability.

Names to remember:


  As per terminology in RDBMS,

                    Database    -   Database
                    Table           -   Collection
                    Row            -   Document.
                    Column       -   Field
                    Joins           -   Embedded Documents.
                    Index           -   Index
                    Partition      -   Shard


We can create multiple databases in one mongo server.

Collection is a group of documents.

Document is a set of key-value pairs that stores in BSON (Binary JSON) format.

No schema required(schema-less) to store data in MongoDB.

Features:


High performance.
High availability.
Horizontal scalability.
Multiple storage engines support.


                                                                                                                                         -- Thiru //