[英]MongoDB Update Array element
I have a document structure like 我有一个类似的文档结构
{
"_id" : ObjectId("52263922f5ebf05115bf550e"),
"Fields" : [
{
"Field" : "Lot No",
"Rules" : [ ]
},
{
"Field" : "RMA No",
"Rules" : [ ]
}
]
}
I have tried to update by using the following code to push into the Rules Array which will hold objects. 我试图通过使用以下代码更新到将保存对象的规则数组。
db.test.update({
"Fields.Field":{$in:["Lot No"]}
}, {
$addToSet: {
"Fields.Field.$.Rules": {
"item_name": "my_item_two",
"price": 1
}
}
}, false, true);
But I get the following error: 但是我收到以下错误:
can't append to array using string field name [Field] 无法使用字符串字段名称追加到数组[Field]
How do I do the update? 我该如何进行更新?
You gone too deep with that wildcard $
. 你用那个通配符$
太深了。 You match for an item in the Fields
array, so you get a access on that, with: Fields.$
. 您匹配Fields
数组中的项目,因此您可以使用以下Fields.$
访问该Fields.$
: Fields.$
。 This expression returns the first match in your Fields
array, so you reach its fields by Fields.$.Field
or Fields.$.Result
. 此表达式返回Fields
数组中的第一个匹配项,因此您可以按Fields.$.Field
访问其Fields.$.Field
或Fields.$.Result
。
Now, lets update the update
: 现在,让我们更新update
:
db.test.update({
"Fields.Field": "Lot No"
}, {
$addToSet: {
"Fields.$.Rules": {
'item_name': "my_item_two",
'price':1
}
}
}, false, true);
Please note that I've shortened the query
as it is equal to your expression. 请注意,我缩短了query
因为它等于你的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.