【发布时间】:2013-07-15 22:34:21
【问题描述】:
让我们假设以下架构:
{
'_id' : 'star_wars',
'count' : 1234,
'spellings' : [
{ spelling: 'Star wars', total: 10},
{ spelling: 'Star Wars', total : 15},
{ spelling: 'sTaR WaRs', total : 5} ]
}
我可以通过这样做来更新计数和其中一个拼写:
db.movies.update(
{_id: "star_wars",
'spellings.spelling' : "Star Wars" },
{ $inc :
{ 'spellings.$.total' : 1,
'count' : 1 }}
)
但是这种形式的更新不适用于 upsert。即,如果我尝试使用不存在的 _id 或使用不存在的拼写进行更新(使用 upsert),则不会发生任何事情。
有没有一种解决方案可以让我在更新 ($inc) 子文档时进行 upsert?
谢谢!
【问题讨论】:
-
使用无效的
upsert显示查询,以便我们为您提供帮助。如果您将上述查询与upsert选项一起使用,则没有定义new spelling,因此最终它不会添加任何内容。它只会更新现有的拼写 -
我已经尝试了上面的查询,带有 upsert 选项。有没有别的写法?我基本上想更新特定拼写的'count'和'total'(每个+1),但是使用upsert(即,如果_id不匹配,将创建整个文档,或者子文档将是如果 _id 匹配但特定拼写不存在则创建)。
-
很公平。感觉一次更新是不可能的。谢谢! :)
标签: mongodb