Refresh nth document in nested array document in mongodb

I need to update a document in an array inside another document in Mongo DB

     {
             "_id": ObjectId ("51cff693d342704b5047e6d8"),
             "author": "test",
             "body": "sdfkj dsfhk asdfjad",
             "comments": [
                     {
                             "author": "test",
                             "body": "sdfkjdj \ r \ nasdjgkfdfj",
                             "email": " test@tes.com "
                     },
                     {
                             "author": "hola",
                             "body": "sdfl \ r \ nhola \ r \ nwork here"
                     }
             ],
             "date": ISODate ("2013-06-30T09: 12: 51.629Z"),
             "permalink": "jaiho",
             "tags": [
                     "jaiho"
             ],
             "title": "JAiHo"
     }


 Q1) Update email of 0th element of comments array
 db.posts.update ({"permalink": "haha"}, {$ set: {"comments.0.email": 1}})
 This doesn't throw any exception but doesn't update anything as well
 Q2) Add a field on nth element of comments array number_likes
 db.posts.update ({"permalink": "haha"}, {$ inc: {"comments.0.num_likes": 1}})
 Doesn't work either.

 Am I missing something here?
+4
source share
2 answers

Q1: If you update the permalink "jaiho" instead of "haha", this will certainly update the email;

> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}}) > db.posts.find() ..., "email" : 1 },... 

Q2: The same applies to this include;

 > db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}}) > db.posts.find() ..., "num_likes" : 1 },... 
+6
source

If you are trying to do this dynamically in Node JS, the following should work.

 i = 0; selector = {}; operator = {}; selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1} operator['$inc'] = selector; // {'$inc' : {'comments.0.num_likes' : 1} } db.posts.update({'permalink' : 'xyz'}, operator); 
+4
source

Source: https://habr.com/ru/post/1488938/


All Articles