2

I am trying to update some matched elements within an array in a mongodb document.

I want to update all the comments.$index.author from chao to tom, but I can't figure out the syntax.

Here's what I want to do in pseudo-json.

Before:

{
 "author" : "lily",
 "contents" : "watch movive",
 "comments" : [
             {
                 "comment" : "good",
                 "author" : "chao",
                 "votes" : 0
             },
             {
                 "comment": "so so",
                 "author": "chao",
                 "votes": 3
             },
             ………………,
             {
                 "comment": "bad",
                 "author": "yong",
                 "votes": -1
             },
         ]
}

After:

{
"author" : "lily",
"contents" : "watch movive",
"comments" : [
             {
                 "comment" : "good",
                 "author" : "tom",
                 "votes" : 0
             },
             {
                 "comment": "so so",
                 "author": "tom",
                 "votes": 3
             },
             ………………,
             {
                 "comment": "bad",
                 "author": "yong",
                 "votes": -1
             },
         ]
 }
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
Chris
  • 51
  • 4
  • what have you attempted? – depperm Mar 20 '18 at 16:31
  • I want to write some python code like this: res = db.posts.find() for post in res: NewPost = post for index in range(len(NewPost["comments"])): if NewPost["comments"][index]["author"] == "chao": NewPost["comments"][index]["author"] = "tom" db.posts.update(post, NewPost) But it failed. Also, I wonder will there be more clever method? – Chris Mar 20 '18 at 16:41

0 Answers0