Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

I have a Mongo document which holds an array of elements.

I'd like to reset the .handled attribute of all objects in the array where .profile = XX.

The document is in the following form:

"_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), 

"user_id": "714638ba-2e08-2168-2b99-00002f3d43c0", "events": [{ 

"handled": 1, 

"profile": 10, 

"data": "....." 

} { 

"handled": 1,

"profile": 10, 

"data": "....." 

} { 

"handled": 1, 

"profile": 20, 

"data": "....." 

... 

  ] 

}

so, I tried the following:

.update({"events.profile":10},{$set:{"events.$.handled":0}},false,true)

However, it updates only the first matched array element in each document. (That's the defined behaviour for $ - the positional operator.)

How can I update all matched array elements?

1 Answer

0 votes
by (106k points)

To update Multiple Array Elements in mongodb you can use the below-mentioned code:-

db.collection.find({ _id: ObjectId('4d2d8deff4e6c1d71fc29a07') })

 .forEach(function (doc) { 

doc.events.forEach(function (event) { 

if (event.profile === 10) { 

event.handled=0; 

    }); 

db.collection.save(doc);

 });

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

Browse Categories

...