Tuesday, March 30, 2021

How to update an array in MongoDb using $ Operator?

 Let's say we have below dataset:

[{

name : "Simon"

hobbies : [

{ title : "badminton", frequency : 2 } ,

{ title : "Swimming", frequency : 1 } 

]

}, 

{

name : "Max"

hobbies : [

{ title : "badminton", frequency : 1 } ,

{ title : "Swimming", frequency : 2 } 

]

},]


$ is a placeholder to update the first element that matches the query condition in the array. For example, below change Simon's hobby from Badminton to Tennis and frequency from 2 to 5. 


db.hobby.updateMany(

    {"hobbies" : {$elemMatch: {title : "badminton", frequency : 2}}}, 

    {$set : {"hobbies.$" : {title : "Tennis", frequency : 5 }}}

);


You can use $[].<fieldname> to update all element in the array. For example, add expert into all hobbies.


db.hobby.updateMany(

    {}, 

    {$set : {"hobbies.$[].expert" : true }}

);


You can add a new element into the array by adding $.<fieldname>. For example, adding expert new field:


db.hobby.updateMany(

    {"hobbies" : {$elemMatch: {title : "Tennis", frequency : 5}}}, 

    {$set : {"hobbies.$.expert" : true }}

);


Reference:
https://docs.mongodb.com/manual/reference/operator/update/

No comments:

Post a Comment