1

使用这样的模式,其中“items”字段包含一个带有嵌套翻译的子文档数组:

{
        "_id" : ObjectId("513740415b51ea0803000001"),
        "items" : [
                {
                        "id" : ObjectId("5137407f5b51ea100f000000"),
                        "title" : {
                                "en" : "Yes",
                                "fr" : "Oui",
                                "es" : "Si"
                        }
                },
                {
                        "id" : ObjectId("5137407f5b51ea100f000003"),
                        "title" : {
                                "en" : "No"
                        }
                }

        ],
}

您将如何将翻译添加到特定项目 id ?

4

2 回答 2

1

您可以使用$位置运算符来更新文档的特定数组元素。

例如,添加"de": "nein"

db.test.update(
    {'items.id': ObjectId("5137407f5b51ea100f000003")}, 
    {$set: {'items.$.title.de': 'nein'}})

$对象中的表示查询选择参数匹配$set的元素的索引。items

于 2013-03-06T14:27:16.263 回答
0

你可以这样做:

db.yourColName.update({"items.id" : "itemId"}, {$set : {"translationField" : "translationValue"}})

在查询的第一部分中,您正在搜索数组中的直接项并为其设置一个新字段 + 值。

问题是,就像您已经注意到的那样,Mongo 没有静态模式。因此$set,要么更新现有字段,要么创建一个新字段。这完全取决于您在子查询中设置的字段名称。

要获取直接文档,请使用$运算符:items.$.title.frwhere$将表示当前对象。

于 2013-03-06T14:19:48.300 回答