mongodb位置运算符错误 [英] mongodb positional operator error

查看:760
本文介绍了mongodb位置运算符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的物体

{
    "_id" : ObjectId("5742be02289512cf98bf63e3"),
    "name" : "test1",
    "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 single query, to update all documents at once. I think, this query will do it

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

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

But when I run this query, I get an error.

代码":16837,
"errmsg":位置运算符未找到 从查询中匹配.未展开的更新:attributes.$.weight"

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

所以我不明白为什么. 请帮助

So I cant understand why. Please help

推荐答案

您需要将数组字段包含在查询文档中,才能使用

You need to include the array field as part of the query document in order to use the positional operator.

例如,如果要更新第一个数组元素,即使用{ "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,您可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆