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?
Correct, the
$pushoperator allows you to update an existing array. You can use the$pushAlloperator to add multiple values in a single query.To add a comment to your example document, the query would be:
These operators are atomic, so you won’t run into any problems if multiple users add comments simultaneously.