MongoDB: 使用 Mongo Shell 从另一个嵌套字段更新嵌套字段

MongoDB: Update nested field from another nested field with dot notation using MongoShell

我想从另一个嵌套字段值更新一个空的嵌套字段。我正在使用这个 Mongo Shell 命令:

db.myCollection.updateMany({"object2.field": ""}, { $set: {"object2.field": '$object1.field' } } );

$object1.field 未解析,目标字段实际上包含变量名称而不是其内容。

我进行了许多测试和文档搜索,但没有成功。

正如turivishal在他的评论中所说:Mongo Shell无法访问另一个字段进行内部操作。 必须使用 update with aggregation pipeline。在这种情况下,只需要将更新部分包裹在数组括号 [{ $set: { "object1.field": "$object2.field" } }].