Mongodb Classroom image

Anil  Bist / Professional / DataBase

 
To post your Question Join Classroom
 
Lesson Topics's No:-  ||
Lessons:-Update of embedded documents

Update of embedded documents

For the following schema:

{name: 'Tom', age: 28,  marks:  [ 50, 60, 70 ] }

 

Update Tom's marks to 55 where marks are 50 (Use the positional operator $):

db . people . update ( { name: "Tom", marks: 50 }, { "$set" : { "marks.$":  55 } } )  

 

For the following schema:

{ name: 'Tom', age: 28, marks: [ { subject:  "English",  marks: 90 },{ subject:  "Maths", marks: 100 },
{ subject: "Computes", marks: 20 } ] } 

 

Update Tom's English marks to 85 :

db. people.update  ( { name:  "Tom""marks.subject" : "English" }, { "$set" : { "marks.$.marks" : 85 } } ) 

 

Explaining above example:

By using {name: "Tom", "marks.subject": "English"} you will get the position of the object in the marks array, where subject is English. In "marks.$.marks", $ is used to update in that position of the marks array 

Update Values in an Array

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the
element in the array.

Consider a collection students with the following documents:

"_id"  : 1"grades"  :  [  80,  8590   ] }
"_id"  : 2"grades"  :  [  88,  90,  92   ] }
"_id"  : 3 "grades"  :  [  85,  10090  ] }

 

To update 80 to 82 in the grades array in the first document, use the positional $ operator if you do not know the position of the element in the array:

db. students.update (
{  _id:  1,  grades:  80  },
{  $set:  {  "grades.$"  : 82 } }
 
 
 
image
Anil  Bist

Skills    Mongodb

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,India
Description:-

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a
Explore

 

  Students (0)