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 //