使用 MongoDB 进行多次原子更新?
我正在使用 Codeigniter 和 Alex Bilbie 的 MongoDB 库。 在我正在开发的 API 中,用户可以上传图像,其他用户可以对其进行评论。 我选择将评论作为图像的子文档包含在内。
每个评论包含:(
- 作者的)全名
- Comment
- Created_at
换句话说。用户的全名被“硬编码”到每个评论中,因此如果他们 后来决定更改他们的名字我有一个问题。
我读到我可以使用原子更新来更新名称的所有出现(如注释中),但是我如何使用 Alex 的库来做到这一点?我可以更新所有名称错误的地方吗?
更新
这是带有注释的图像文档的样子。 我认为 MongoDB 鼓励使用子文档但却不包含更新数组中多个项目的方法,这很奇怪。
{
"_id": ObjectId("4e9ead773dc793dc01020000"),
"description": "An image",
"category": "accident",
"comments": [
{
"id": ObjectId("4e96bd063dc7937202000000"),
"fullname": "James Bond",
"comment": "This is a comment.",
"created_at": "2011-10-19 13:02:40"
}
],
"created_at": "2011-10-19 12:59:03"
}
感谢所有帮助!
I am using Codeigniter and Alex Bilbie's MongoDB library.
In my API that I am developing users can upload images and other users can comment on them.
I have chosen to include the comments as sub documents to the images.
Each comment contains:
- Fullname (of author)
- Comment
- Created_at
So in other words. The users full name is "hard coded" into each comment so if they
later decides to change their names I have a problem.
I read that I can use atomic updates to update all occurrences of the name (like in comments) but how can I do this using Alex´s library? Can I update all places where the name is wrong?
UPDATE
This is how the image document looks like with the comments.
I think that it is pretty strange that MongoDB encourage the use of subdocuments but then does not include a way to update multiple items in an array.
{
"_id": ObjectId("4e9ead773dc793dc01020000"),
"description": "An image",
"category": "accident",
"comments": [
{
"id": ObjectId("4e96bd063dc7937202000000"),
"fullname": "James Bond",
"comment": "This is a comment.",
"created_at": "2011-10-19 13:02:40"
}
],
"created_at": "2011-10-19 12:59:03"
}
Thankful for all help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不熟悉 codeignitor,但是 mb mongodb shell 语法会帮助你:
最后一个 true 标志表明你想要更新多个文档。因此可以在一次更新操作中更新所有注释。
顺便说一句:对 mongodb 和 nosql 中的数据进行非规范化(不是“硬编码”)通常是常规操作。此外,需要更新大量文档的操作通常是异步进行的。但这取决于你。
更新:
但是,上面的查询将更新嵌套数组的第一个注释中的全名。如果您需要影响多个数组元素的更改,则需要使用多个更新语句。
I am not familiar with codeignitor, but mb mongodb shell syntax will help you:
Last true flag indicate that you want update multiple documents. So it is possible to update all comments in one update operation.
BTW: denormalazing (not 'hard coding') data in mongodb and nosql in general is usual operation. Also operation that require update a lot of documents usually work async. But it is up to you.
Update:
But, above query will update full name in first comment on nested array. If you need to affect changes to more than one array element you will need to use multiple update statements.