Mongodb error: The positional operator did not find the match needed from the query

Mongodb error: The positional operator did not find the match needed from the query

我有一个 collection 和 objects 像这样

{
    "_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
}

而且我想更新所有文档,并为每个属性设置新字段。 所以我想 运行 一个查询来一次更新所有文档。我想,这个查询会做

db.spaces.update({}, { $set: { "attributes.0.weight": 2 } }, {multi: true})

但是当我运行这个查询时,我得到一个错误:

"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: attributes.$.weight"

我不明白为什么。 请帮忙

您需要将数组字段作为查询文档的一部分,才能使用 positional operator.

例如,如果您想更新第一个数组元素,即使用 { "attributes.name": "x" },那么您可以遵循以下模式:

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() 方法根据上面的过滤器。

位置运算符需要来自更新查询的匹配部分的匹配项。

例如:

db.spaces.update({ "attributes.name": "x" }, { $set: { "attributes.0.weight": 2 } }, {multi: true})

此处更新操作的第一个参数将匹配数组attributes,其中任何元素都有属性 name=="x",对于任何匹配条件的元素都可以使用位置运算符更新它。

所以,因为 name='x',在这种情况下,第一个匹配元素将是,

{
            "name" : "x",
            "color" : "0xd79c9c",
            "_id" : ObjectId("5742be02289512cf98bf63e8")
        }, 

它会得到更新。

现在从你的问题中我了解到你想要更新文档的方式是在每个文档中你的第一个元素 attribute 获得 weight=2 的新值。

你可以这样做

db.spaces.update({ "attributes.name": { $regex: /^(?=[\S\s]{10,8000})[\S\s]*$/ } }, { $set: { "attributes.0.weight": 2 } }, {multi: true})

我们在这里做的是匹配数组属性中的所有元素。我们使用位置运算符更新该数组的第一个元素