0

I'm trying to update the comment_delete = 'false' to 'true' on the second object within an array. Help Please ....

 

"_id" : "jLkRdxocZzheefWF3",
 "comments" : [
  {
   "comment_id" : "\u0003624334",
   "comment" : " test",
   "user" : "peter pan",
   "userId" : "MQtp4i8bZeLYSLbr5",
   "comment_delete" : "false"
  },
  {
   "comment_id" : "\u0007973101",
   "comment" : " add",
   "user" : "peter pan",
   "userId" : "MQtp4i8bZeLYSLbr5",
   "comment_delete" : "false"
  }
 ],
 
}
er ic
  • 1
  • 2
  • `comments[1].comment_delete = true` – MysterX Apr 17 '18 at 14:25
  • Possible duplicate of [MongoDB - Update objects in a document's array (nested updating)](https://stackoverflow.com/questions/10522347/mongodb-update-objects-in-a-documents-array-nested-updating) – MasterAM Apr 18 '18 at 06:48

2 Answers2

0

Try this query:

db.collection.update(
{_id:"jLkRdxocZzheefWF3"}, //add your first match criteria here, keep '{}' if no filter needed.
{$set:{"comments.$[element].comment_delete":"true"}},
{arrayFilters:[{"element.comment_id":"\u0007973101"}]}
)

I dont have an idea about your match criteria since you didnt mention it in the question. Change them as per your requirements. This change comment_delete to true as per the comment_id mentioned.

Output is:

{
"_id" : "jLkRdxocZzheefWF3",
"comments" : [ 
    {
        "comment_id" : "\u0003624334",
        "comment" : " test",
        "user" : "peter pan",
        "userId" : "MQtp4i8bZeLYSLbr5",
        "comment_delete" : "false"
    }, 
    {
        "comment_id" : "\u0007973101",
        "comment" : " add",
        "user" : "peter pan",
        "userId" : "MQtp4i8bZeLYSLbr5",
        "comment_delete" : "true"
    }
 ]
}
Rahul Raj
  • 3,197
  • 5
  • 35
  • 55
  • Thanks Rahul , but I'm still having some error updating, update failed: MongoError: cannot use the part (comments of comments.$[test].comment_delete) to traverse the element ({comments: [ { comment_id: "\u0007973101"...... – er ic Apr 17 '18 at 19:15
  • U need to have mongo version 3.6. And the query should be executed from mongo shell (just in case if you're using third party tool). The above query is tested and its working on my local. Secondly, I dont answer based on your demand (you have un-selected my answer to get instant reply from me). – Rahul Raj Apr 17 '18 at 19:22
0
db.users.update({'_id':'jLkRdxocZzheefWF3',"comments.comment_id":"\u0007973101"},{$set:{'comments.$.comment_delete':true}})
  1. Try above mentioned query it works