MongoDB - How to Update Documents in MongoDB using Robo 3T - TechDB

Latest

All about Database Programming, Performance Tuning and Best Practices.

BANNER 728X90

Friday, 10 January 2020

MongoDB - How to Update Documents in MongoDB using Robo 3T



MongoDB provides the update() command to update the documents of a collection. To update only the documents you want to update, you can add a criteria to the update statement so that only selected documents are updated.

db.collection.update(query, update, options)

By default, the db.collection.update() method updates a single document. To update multiple documents, use the multi option.

Syntax:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2
   }
)


The db.collection.update() method takes the following parameters:

Parameter Type Description
Query Document The selection criteria for the update. The same query selectors as in the find() method are available.
Update Document or pipeline The modifications to apply.
Option
Upsert Boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.
multi Boolean Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false.
wrireConcern Document Optional. A document expressing the write concern. Omit to use the default write concern w: 1.
Collation Document Optional: Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
arrayFilters Array Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
Hint Document or string Optional. A document or string that specifies the index to use to support the query predicate.

Let take an example to update the document or documents using update method. Side by side we can also check the RDBMS syntax to better understanding.

First check the how many documents we have in an inventory collection in TechDB database.



Example - 1

Update the document where item = “mat” and set the new value of qty = 100 and size.h=30
Lets first find the document where item = “mat”. We found 1 document only.




MongoDB Update method
RDBMS syntax
db.inventory.update(
    {"item":"mat"},
    {$set:
        {"qty":100,"size.h":30}
    }
)
Update inventory
Set qty = 100, h=30
Where item = “mat”
Explanation:
{“item”:”mat”} -- query parameter
Update parameter and $set is update operator.
{$set:
        {"qty":100,"size.h":30}
}
Option parameter is optional

Where item = “mat” -- Filter criteria

Let's check the document updated or not.

db.inventory.find({item:"mat"})


You can see above document updated successfully. qty = 100 and size.h = 30.0

Example - 2

Let's update the document or documents where status = “A” and set the new value of qty = 10
first find the document where status = “A”. We found 6 documents in inventory collection.


MongoDB Update method RDBMS syntax
db.inventory.update(
    {"status":"A"},
    {$set:
        {"qty":10}
    }
)
Update inventory
Set qty = 10
Where status = “A”
Only 1 document updated All records updated


Lets view the documents again where status = “A”


You can see only 1 document updated with qty = 10. This happened because by Default Update() method updates a single document . To update multiple documents, use the multi option in option parameter.

Lets run the same update statement with multi = true

Syntax:
db.inventory.update(
    {"status":"A"},
    {$set:
        {"qty":10}
    },
    {
      Multi : true
    }
)



Lets check the documents updated or not in inventory collection.


db.inventory.find({status:"A"})


Now all the documents updated with qty = 10.


Example - 3

Update the document where item = “canvas”. I have added few elements / fields in this documents to understand the update.


Let check first what and how the document looks like before update. We have only one document that meet the search criteria where item = “canvas”

In this document we have 

Size have 3 fields
"size" : { "h" : 28.0, "w" : 35.5, "uom" : "cm"}

Color have 2 elements
“color” : [“red”,”black”]

Ratings have 2 elements and each element have 2 fields. In this example we are going to update 2nd element (highlighted).
"ratings" : [ {"by" : "abc","rating" : 2}, {"by" : "xyz","rating" : 4} ]

Now we are going to update these fields and elements.

db.inventory.update(
   { item : "canvas" },
   {
     $inc: { qty: 125 },
     $set: {
       "size.h": 31,
       "color": [ "brown" ],
       "ratings.1": { "by": "sk", "rating": 5 }
     }
   }
)



The result should be

Before Update After Update Description
Qty = 10 Qty = 10+125 = 135 $inc operator increments a field by a specified value
Size.h = 28.0 Size.h = 31.0 Size.h means update only “h”
Update the size.h value by $set operator
Color = red, black Color = brown Update the array element by $set operator
Ratings.1
by = “xyz” and /n rating=4
Ratings.1
by = “sk” and rating=5
Ratings.1 means 2nd element and Ratings.0 means 1st element.
Update the fields of an array element by $set operator
Now check the documents updated or not.
You can see all the fields of Document updated successfully.


No comments:

Post a Comment