Mongodb 错误:位置运算符未从查询中找到所需的匹配项 [英] Mongodb error: The positional operator did not find the match needed from the query
问题描述
我有一个像这样的对象的集合
I have a collection with objects like this
{
"_id" : ObjectId("5742be02289512cf98bf63e3"),
"name" : "test1",
"attributes" : [
{
"name" : "x",
"color" : "0xd79c9c",
"_id" : ObjectId("5742be02289512cf98bf63e8")
},
{
"name" : "y",
"color" : "0xd79c9c",
"_id" : ObjectId("5742be02289512cf98bf63e7")
},
{
"name" : "z",
"color" : "0xd79c9c",
"_id" : ObjectId("5742be02289512cf98bf63e6")
}
],
"__v" : 6
}
而且我想更新所有文档,并为每个属性设置新字段.所以我想运行一个查询来一次更新所有文档.我想,这个查询会做
And I want to update all documents, and set for each attribute new field. So I want to run a single query to update all documents at once. I think, this query will do
db.spaces.update({}, { $set: { "attributes.0.weight": 2 } }, {multi: true})
但是当我运行这个查询时,我得到一个错误:
But when I run this query, I get an error:
代码":16837,
错误消息": "位置运算符没有找到查询所需的匹配.未扩展更新:attributes.$.weight"
"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: attributes.$.weight"
我不明白为什么.请帮忙
I can't understand why. Please help
推荐答案
为了使用 位置运算符
.
例如,如果您想更新第一个数组元素,即使用 { "attributes.name": "x" }
那么您可以遵循以下模式:
For example, if you want to update the first array element i.e. with { "attributes.name": "x" }
then you could follow the pattern:
db.spaces.update(
{ "attributes.name": "x" }, // <-- the array field must appear as part of the query document.
{ "$set": { "attributes.$.weight": 2 } },
{ "multi": true }
)
对于较新的 MongoDB 版本 3.2.X
,您可以使用 updateMany()
方法根据上面的过滤器更新集合中的多个文档.
For the newer MongoDB versions 3.2.X
, you could use the updateMany()
method to update multiple documents within the collection based on the filter above.
这篇关于Mongodb 错误:位置运算符未从查询中找到所需的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!