我有一个Collection 像这样的东西

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

我想更新所有文档,并 for each 属性设置新字段.

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"

我不明白为什么.

推荐答案

为了使用100,需要将数组字段作为查询文档的一部分.

例如,如果要更新第一个数组元素,即使用{ "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,可以使用100方法基于上述过滤器更新集合中的多个文档.

Mongodb相关问答推荐

geoLocation或geoNear为坐标和半径使用let变量

会话的Mongo-go驱动程序版本.Copy()

筛选出嵌套数组中的记录Mongo DB聚合

在数组对象 Mongodb 中仅 Select 需要的数组

使用特定关键字和邻近度进行查询和过滤

如何对 MongoDB setWindowFields 中当前文档以外的文档进行操作

构造函数的参数 0 需要错误类型的 bean

Mongo 聚合将 $sort 与 $geoNear 结合使用

以聚合顺序使用 $$ROOT

Spring Data + MongoDB GridFS 可以通过 Repository 访问吗?

在 MongoDB 中创建简短、唯一的对象 ID

mongodb上不区分大小写的查询

通过 Spring Boot 应用程序访问 mongodb 时的身份验证错误

MongoDB展开多个数组

Mongoose 中不同集合的相同模式

MongoDB 中的多个 $inc 更新

mongo dbname --eval 'db.collection.find()' 不起作用

如何在mongoose的嵌套填充中 Select 特定字段

Mongoid 不在查询中

Mongoose upsert 不创建默认模式属性