如果嵌套字段的路径不是恒定的,则更新它 [英] Update nested field if a path to it isn't constant

查看:77
本文介绍了如果嵌套字段的路径不是恒定的,则更新它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB的Django上工作. 其中一个集合具有以下结构:

I'm working on Django which uses MongoDB. One of collections has the following structure:

{
    "inspectionType" : {
        "id" : "59a79e44d12b52042104c1e8",
        "name" : "Example Name",
        "inspMngrsRole" : [
            {
                "id" : "55937af6f3de6c004bc42862",
                "type" : "inspectorManager",
                "is_secret_shoper" : false
            }
        ],
        "scopes" : {
            "56fcf6736389b9007a114b10" : {
                "_cls" : "SomeClass",
                "id" : "56fcf6736389b9007a114b10",
                "name" : "Example Name",
                "category" : "Example Category"
            },
        }
    }
}

我需要为集合中的所有文档更新字段"_cls"("inspectionType.scopes .._ cls"). 问题是scope_id是动态的,并且对于每个范围都是唯一的. 可以使用db.collection.update吗? 以及通往田野的路径应该是什么样的?

I need to update field "_cls" ("inspectionType.scopes.._cls") for all documents in the collection. The problem is the scope_id is dynamic and unique for each scope. Is it possible to use db.collection.update for that? And how should the path to the field look like?

更新: MongoDB版本:3.6.7

Update: MongoDB version: 3.6.7

推荐答案

您可以使用聚合(如果您使用的MongoDB版本低于4.2)进行更新,还可以使用更新操作 updateMany方法(如果使用4.2或更高版本),如下所示:

You can update using an aggregation (if you are using MongoDB version lesser than 4.2) plus an update operation or the updateMany method (if using version 4.2 or later) as follows:

# 1

var NEW_VALUE = "some new value"    // the value to be updated

db.collection.aggregate( [
  { 
      $addFields: { 
          "inspectionType.scopes": { $objectToArray: "$inspectionType.scopes" } 
      } 
  },
  { 
      $addFields: { 
          "inspectionType.scopes.v._cls": NEW_VALUE 
      } 
  },
  { 
      $addFields: { 
           "inspectionType.scopes": { $arrayToObject: "$inspectionType.scopes" } 
      } 
  }
] ).forEach( doc => db.scopes.updateOne( { _id: doc._id }, { $set: { "inspectionType.scopes": doc.inspectionType.scopes } } ) )


从MongoDB 4.2版开始,updateMany可以使用聚合管道进行更新操作;参见使用聚合更新管道.


Starting MongoDB version 4.2 the updateMany can use an aggregation pipeline for the update operation; see Update with Aggregation Pipeline.

# 2

db.collection.updateMany(
  { },
  [
      { 
          $set: { 
              "inspectionType.scopes": { $objectToArray: "$inspectionType.scopes" } 
          } 
      },
      { 
          $set: { 
              "inspectionType.scopes.v._cls": NEW_VALUE 
          } 
      },
      { 
          $set: { 
               "inspectionType.scopes": { $arrayToObject: "$inspectionType.scopes" } 
          } 
      }
  ]
)

这篇关于如果嵌套字段的路径不是恒定的,则更新它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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