MongoDB - How to Update Array fields as part of Documents in MongoDB using Robo 3T - I - TechDB

Latest

All about Database Programming, Performance Tuning and Best Practices.

BANNER 728X90

Thursday, 16 January 2020

MongoDB - How to Update Array fields as part of Documents in MongoDB using Robo 3T - I



Lets check how to update array field as part of the document. There are few Array update Operators and Modifiers available to update Array fields of the documents.

Array Update Operators
$addToSet Adds elements to an array only if they do not already exist in the set.
$pop Removes the first or last item of an array.
$pull Removes all array elements that match a specified query.
$push Adds an item to an array.
$pullall Removes all matching values from an array

Update Operator Modifiers
$each Modifies the $push and $addToSet operators to append multiple items for array updates.
$position Modifies the $push operator to specify the position in the array to add elements.
$slice Modifies the $push operator to limit the size of updated arrays.
$sort Modifies the $push operator to reorder documents stored in an array.



Example - 1:
Update single array element using $addtoset


Initially no elements found in “color” where item = “canvas”


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


Lets add below color for item “canvas” using $addtoset


db.inventory.update(
   { item : "canvas" },
   {
     $addToSet: {"color":"blue"}
   }
)



Elements added successfully. Lets check how the array looks now.


Take an another example where we are trying to add multiple elements in one command using $addtoset and $each operator.


Example – 2 Update one or more elements using $addtoset and $each operator.
Lets check how to add new elements or fields in existing documents



db.inventory.update(
   { item : "canvas" },
   {
     $addToSet: {"color":{$each:["blue","black","red"]}}
   }
)



Elements added successfully. Lets check how the array looks now.

color[0]=”blue” already exist and it has not added because $addtoset add elements only if the elements does not exists in the document.


Example – 3 In this example we are trying to add fields (Object)

Initially we have only 3 elements and 2 fields.



Update the document with new ratings.


db.inventory.update(
   { item : "canvas" },
   {
     $addToSet: {"ratings": {$each:[{"by":"kk","rating":7}]}}
   }
)



Check the document, how ratings added.


Similarly we can add multiple elements in one command.


db.inventory.update(
   { item : "canvas" },
   {
     $addToSet: {"ratings": {$each:[
                                    {"by":"ad1","rating":8},
                                    {"by":"ad2","rating":9}
                                   ]}}
   }
)



Lets check the elements added in documents successfully.



No comments:

Post a Comment