Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

mongodb - Update key in nested document

I would like to update the keys of the object "values" in the following document stored in a MongoDB collection:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_Avg": 13,
            "BB_Avg": 19,
            "CC_Avg": 18
        }
    }
}

To make it looks like this:

{
    "data": {
        "name": "Doe",
        "values": {
            "AA_MT": 13,
            "BB_MT": 19,
            "CC_MT": 18
        }
    }
}
question from:https://stackoverflow.com/questions/65830503/update-key-in-nested-document

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dynamic update you can use update with aggregation pipeline starting from MongoDB 4.2,

First approach: using $rpelaceOne,

  • $objectToArray convert data.values from object to array in k and v format
  • $map to iterate loop of above converted array
  • $replaceOne will replace string on the base of input and replacement
  • $arrayToObject back to convert from array to object
db.collection.update({},
  [{
    $set: {
      "data.values": {
        $arrayToObject: {
          $map: {
            input: { $objectToArray: "$data.values" },
            in: {
              k: {
                $replaceOne: {
                  input: "$$this.k",
                  find: "Avg",
                  replacement: "MT"
                }
              },
              v: "$$this.v"
            }
          }
        }
      }
    }
  }
])

Playground


Second approach: using $split, $arrayElemAt, $concat,

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...