mongodb:更新元素? [英] mongodb: updating elements?
问题描述
我(和大多数人一样)来自 mySQL 背景,试图切换到 noSQL 和 mongoDB.由于非规范化是 noSQL 的一部分,因为连接是不可能的,所以我将如何设计一个简单的博客:
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?
是我在 mongoDB 中处理的 push
函数吗?
Is it the push
function I am looking after in mongoDB?
推荐答案
正确,$push
运算符允许您更新现有数组.您可以使用 $pushAll
运算符在单个查询中添加多个值.
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.
这篇关于mongodb:更新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!