I have collection with the following document:
{
"_id" : ObjectId("56cbf9cd75de3ee9057b23c7"),
"title" : "Abc",
"comments" : [
{
"_id" : "",
"message" : "",
"active" : 1,
"status" : 1,
},
{
"_id" : "",
"message" : "",
"active" : 0,
"status" : 1,
},
{
"_id" : "",
"message" : "",
"active" : 1,
"status" : 1,
}
],
}
{
"_id" : ObjectId("553744ae75de3eb9128b4568"),
"title" : "Jhon",
"comments" : [
{
"_id" : "",
"message" : "",
"active" : 1,
"status" : 1,
}
]
}
I need to update all status of comments as 0 where comments.active=1. I tried to solve it as below, but only first record of the comments is updated. Please help me..
db.comments.update({'comments.active':1},{$set:{'comments.$.status':0}})
Per this issue New operator to update all matching items in an array
, currently there is no operation to do that in mongodb. Feel so sad, this issue lasts for 6 years.
There could be one work around in mongo shell as below.
> db.comments
.find({})
.forEach(function(doc) {
doc.comments.map(function(c) {
if (c.active == 1) {
c.status = 0;
}
});
db.comments.update(
{_id: doc._id},
{$set: {comments: doc.comments}});
});