MongoDB:更新和子文档 [英] MongoDB: Upserting and Sub documents
本文介绍了MongoDB:更新和子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们假设以下架构:
{
'_id' : 'star_wars',
'count' : 1234,
'spellings' : [
{ spelling: 'Star wars', total: 10},
{ spelling: 'Star Wars', total : 15},
{ spelling: 'sTaR WaRs', total : 5} ]
}
我可以通过这样做来更新计数和拼写之一:
I can update the count and one of the spellings by doing this:
db.movies.update(
{_id: "star_wars",
'spellings.spelling' : "Star Wars" },
{ $inc :
{ 'spellings.$.total' : 1,
'count' : 1 }}
)
但是这种形式的更新不适用于 upsert.即,如果我尝试使用不存在的 _id 或拼写不存在的 _id 进行更新(使用 upsert),则不会发生任何事情.
But this form of update doesn't work with upsert. i.e., if I try to update (with upsert) with an _id that doesn't exist, or with a spelling that doesn't already exist, nothing happens.
有没有一种解决方案可以让我在更新 ($inc) 子文档时进行 upsert?
Is there a solution that allows me to upsert when updating ($inc) a sub-document?
谢谢!
推荐答案
不过,您可以稍微更改一下架构.如果您的文档如下所示:
You could change your schema a little, though. If your documents looked like this:
{
'_id' : 'star_wars',
'count' : 1234,
'spellings' :
{
'Star wars': 10,
'Star Wars': 15,
'sTaR WaRs': 5
}
}
您的更新将变得如此简单:
Your updates would become as simple as:
db.movies.update({_id:"star_wars"},{$inc:{"spellings.Star Wars":1}},true)
这篇关于MongoDB:更新和子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文