mongodb: updating elements?
I am (as most ) coming from a mySQL background trying to sw开发者_C百科itch 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?
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.
精彩评论