mongodb: updating elements?

人盡茶涼 提交于 2019-12-11 06:21:10

问题


I am (as most ) coming from a mySQL background trying to switch over to noSQL and mongoDB. Since denormalization is a part of noSQL since joins is impossible, here's how I would design a simple blog:

array (
    blog_title => 'my blogpost',
    'date' => '2010-09-05',
    comments => array (
        '1' => 'Such a good post!!! You deserve a nobel prize'
    )
);

If I want to update the comments, adding a new element in that array, how can I make sure that this is done and not the whole comments array being overwritten if multiple users are trying to write a comment at the same time?

Is it the push function I am looking after in mongoDB?


回答1:


Correct, the $push operator allows you to update an existing array. You can use the $pushAll operator to add multiple values in a single query.

To add a comment to your example document, the query would be:

db.posts.update({blog_title: "my blogpost"}, {$push: {comments: "New comment"}})

These operators are atomic, so you won't run into any problems if multiple users add comments simultaneously.



来源:https://stackoverflow.com/questions/3645961/mongodb-updating-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!