在嵌入式文档中“更新" [英] 'upsert' in an embedded document

查看:76
本文介绍了在嵌入式文档中“更新"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下数据集:

{  
    'component_id':1,  
    '_locales':[   
        {  
            'url': 'dutch',  
            'locale': 'nl_NL'  
        } 
    ] (etc)
}

如果我想使用语言环境更新行,我将运行类似于:

If I want to update the row with the locale I would run something similar to:

db.components.update(
    {'component_id': 1, '_locales.locale': 'nl_NL'},
    {$set: {'_locales.$': {'url': 'new url','locale':'nl_NL'}}, 
    true
);

这可以正常工作,除非该语言环境不存在:

This works fine untill the locale does not exists:

db.components.update(
    {'component_id': 1, '_locales.locale': 'en_US'},
    {$set: {'_locales.$': {'url': 'new url','locale':'en_US'}}, 
    true
);

由于component_id上有一个唯一索引,因此会抛出异常,抱怨键重复.

since there is a unique index on component_id this will throw an exception complaining about a duplicate key.

有没有一种方法可以自动添加具有不同区域设置的新文档",如果已有的话,还可以对其进行更新?根据文档,使用位置运算符不能与"upserting"一起使用.

Is there a way to automatically add the new 'document' with a different locale and update it if it already exists? According to the documentation using the position operator will not work with 'upserting'.

推荐答案

您可以使用 $ addToSet 添加到集合中,以确保没有重复的数组元素,但这不适用于您的更新"情况.

You can use $addToSet to add to a set making sure there is no duplicate array element, but that will not work for your "updating" case.

为了做您想做的事,您需要将数据结构更改为以下内容:

In order to do what you want, you will need to change your data structure to something like:

{
    "_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
    "component_id" : 1,
    "_locales" : {
        "nl_NL" : {
            "url" : "dutch"
        }
    }
}

现在,您可以使用以下命令对nl_NL语言环境进行更新:

Now you can do an update on the nl_NL locale with just:

db.components.update( { component_id: 1 }, { $set: { '_locales.nl_NL.url' : 'new url' } }, true );

新的语言环境也可以使用,例如:

And a new locale will work as well, such as with:

db.components.update( { component_id: 1 }, { $set: { '_locales.en_US.url' : 'American' } }, true );

您可能还想考虑将语言环境作为嵌套对象的一部分,例如:

You might want to consider to having the locale as part of the nested object as well perhaps, like in:

{
    "_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
    "component_id" : 1,
    "_locales" : {
        "nl_NL" : {
            "url" : "dutch"
            "locale" : "nl_NL"                 
        }
    }
}

在某些情况下,这使得检索数据更加容易.

This makes it easier to retrieve data in some cases.

这篇关于在嵌入式文档中“更新"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆