我目前有以下数据集:
{
'component_id':1,
'_locales':[
{
'url': 'dutch',
'locale': 'nl_NL'
}
] (etc)
}
Run Code Online (Sandbox Code Playgroud)
如果我想用语言环境更新行,我会运行类似于:
db.components.update(
{'component_id': 1, '_locales.locale': 'nl_NL'},
{$set: {'_locales.$': {'url': 'new url','locale':'nl_NL'}},
true
);
Run Code Online (Sandbox Code Playgroud)
这很好,直到语言环境不存在:
db.components.update(
{'component_id': 1, '_locales.locale': 'en_US'},
{$set: {'_locales.$': {'url': 'new url','locale':'en_US'}},
true
);
Run Code Online (Sandbox Code Playgroud)
因为component_id上有一个唯一索引,所以会抛出一个抱怨重复键的异常.
有没有办法自动添加具有不同语言环境的新"文档"并更新它(如果它已经存在)?根据使用位置运算符的文档将无法使用'upserting'.
Der*_*ick 12
您可以使用$ addToSet添加到集合中,确保没有重复的数组元素,但这不适用于您的"更新"情况.
为了做你想做的事,你需要将你的数据结构改为:
{
"_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
"component_id" : 1,
"_locales" : {
"nl_NL" : {
"url" : "dutch"
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用以下命令对nl_NL语言环境进行更新:
db.components.update( { component_id: 1 }, { $set: { '_locales.nl_NL.url' : 'new url' } }, true );
Run Code Online (Sandbox Code Playgroud)
一个新的语言环境也可以使用,例如:
db.components.update( { component_id: 1 }, { $set: { '_locales.en_US.url' : 'American' } }, true );
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑将语言环境作为嵌套对象的一部分,例如:
{
"_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
"component_id" : 1,
"_locales" : {
"nl_NL" : {
"url" : "dutch"
"locale" : "nl_NL"
}
}
}
Run Code Online (Sandbox Code Playgroud)
这使得在某些情况下更容易检索数据.
| 归档时间: |
|
| 查看次数: |
4645 次 |
| 最近记录: |