update nth document in a nested array document in mongodb

前端 未结 2 1738
礼貌的吻别
礼貌的吻别 2021-01-03 08:31

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


    {
            \"_id\" : ObjectId(\"51cff693d342704b5047e6d8\"),
            \"aut         


        
相关标签:
2条回答
  • 2021-01-03 09:17

    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);
    
    0 讨论(0)
  • 2021-01-03 09:25

    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 },...
    
    0 讨论(0)
提交回复
热议问题