update nth document in a nested array document in mongodb

倖福魔咒の 提交于 2019-11-30 15:21:18

Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;

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

Q2: Same goes for this include;

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

If you are trying to do it dynamically in Node JS 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!