Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Mongodb: Get value from $[<identifier>] in update

I want to rename a field inside a object itself inside a nested array. As example, I want to rename the all tags m2 to m6 in this document:

{
"_id": 1,
"tagsGroup": [
  {
    "id": "1234",
    "tags": {
      "m1": 1,
      "m2": 2
    }
  },
  {
    "id": "456",
    "tags": {
      "m3": 1,
      "m2": 2
    }
  },
  {
    "id": "1234",
    "tags": {
      "m4": 2,
      "m5": 2
    }
  },
  
]
}

This is my current state of work:

db.collection.update({},
{
  "$set": {"tagsGroup.$[tGp].tags.m6": "$tagsGroup.$[tGp].tags.m2"},
  "$unset": {"tagsGroup.$[tGp].tags.m2": ""}
},
{
  arrayFilters: [{"tGp.tags.m2": {$exists: 1}}],
  multi: true}
)

Unfortunately, the $tagsGroup.$[tGp].tags.m6 is not interpreted. Do you guys, have a way to do this?

Thanks!

question from:https://stackoverflow.com/questions/65950455/mongodb-get-value-from-identifier-in-update

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

1 Answer

0 votes
by (71.8m points)

Probably similar to this question MongoDB rename database field within array,

There is no straight way to rename fields within arrays with a single command. You can try update with aggregation pipeline starting from MongoDB v4.2,

  • $map to iterate loop of tagsGroup array
  • $map to iterate loop of tags object after converting to array using $objectToArray, it will return in k and v format
  • $replaceOne will replace specific string on find field, this is starting from MongoDB v4.4
  • $arrayToObject convert tags array returned by second $map back to object format
  • $mergeObjects to merge current object with updated tags object
db.collection.update(
  { "tagsGroup.tags.m2": { $exists: true } },
  [{
    $set: {
      tagsGroup: {
        $map: {
          input: "$tagsGroup",
          in: {
            $mergeObjects: [
              "$$this",
              {
                tags: {
                  $arrayToObject: {
                    $map: {
                      input: { $objectToArray: "$$this.tags" },
                      in: {
                        k: {
                          $replaceOne: {
                            input: "$$this.k",
                            find: "m2",
                            replacement: "m6"
                          }
                        },
                        v: "$$this.v"
                      }
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }],
  { multi: true }
)

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...