更新MongoDB中精确元素数组中的字段

时间:2021-12-14 17:56:21

I have a document structured like this:

我有一个这样的文档:

{    _id:"43434",    heroes : [        { nickname : "test",  items : ["", "", ""] },        { nickname : "test2", items : ["", "", ""] },    ]}

Can I $set the second element of the items array of the embedded object in array heros with nickname "test" ?

我可以用昵称“test”设置数组heros中嵌入对象的items数组的第二个元素吗?

Result:

结果:

{    _id:"43434",    heroes : [        { nickname : "test",  items : ["", "new_value", ""] }, // modified here        { nickname : "test2", items : ["", "", ""] },    ]}

1 个解决方案

#1


117  

You need to make use of 2 concepts: mongodb's positional operator and simply using the numeric index for the entry you want to update.

您需要使用2个概念:mongodb的位置运算符,只需使用数字索引来表示要更新的条目。

The positional operator allows you to use a condition like this:

位置运算符允许您使用如下条件:

{"heros.nickname": "test"}

and then reference the found array entry like so:

然后像这样引用找到的数组条目:

{"heros.$  // <- the dollar represents the first matching array key index

As you want to update the 2nd array entry in "items", and array keys are 0 indexed - that's the key 1.

因为你想更新“items”中的第二个数组条目,并且数组键被索引为0 - 这就是键1。

So:

所以:

> db.denis.insert({_id:"43434", heros : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});> db.denis.update(    {"heros.nickname": "test"},     {$set: {        "heros.$.items.1": "new_value"    }})> db.denis.find(){    "_id" : "43434",     "heros" : [        {"nickname" : "test", "items" : ["", "new_value", "" ]},        {"nickname" : "test2", "items" : ["", "", "" ]}    ]}

#1


117  

You need to make use of 2 concepts: mongodb's positional operator and simply using the numeric index for the entry you want to update.

您需要使用2个概念:mongodb的位置运算符,只需使用数字索引来表示要更新的条目。

The positional operator allows you to use a condition like this:

位置运算符允许您使用如下条件:

{"heros.nickname": "test"}

and then reference the found array entry like so:

然后像这样引用找到的数组条目:

{"heros.$  // <- the dollar represents the first matching array key index

As you want to update the 2nd array entry in "items", and array keys are 0 indexed - that's the key 1.

因为你想更新“items”中的第二个数组条目,并且数组键被索引为0 - 这就是键1。

So:

所以:

> db.denis.insert({_id:"43434", heros : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});> db.denis.update(    {"heros.nickname": "test"},     {$set: {        "heros.$.items.1": "new_value"    }})> db.denis.find(){    "_id" : "43434",     "heros" : [        {"nickname" : "test", "items" : ["", "new_value", "" ]},        {"nickname" : "test2", "items" : ["", "", "" ]}    ]}