0

I am trying to refactor all the keys over a bunch of collections that match a certain regex or have the same name. The issue is that in different documents or collections, the keys in question may appear at different nesting levels in different locations.

For example, let's say we need to replace the key "sound" to "noise" in the following:

Animals collection:

{
  "_id": "4ebb8fd68f7aaffc5d287383",
  "animal": "cat",
  "name": "fluffy",
  "type": "long-haired",
  "sound": "meow"
}

Events collection:

{
  "_id": "4ebb8fd68f7abac75d287341",
  "event": "thunder",
  "description": {
    "type": "natural",
    "sound": "boom"
  }
}

How would you go about doing it? Via raw mongo queries ideally, or pymongo if necessary

fuzzKitty
  • 334
  • 3
  • 7
  • You may be looking for [idea in this SO answer](https://stackoverflow.com/a/3011885/14732669). It uses mapReduce and recursion to process nested/array structure. – ray Oct 17 '21 at 14:10
  • If it's a one-time thing then I would just copy-pasta the rename query: db.animals.updateMany({}, {$rename: { "sound": "noise"}}); db.events.updateMany({}, {$rename: { "description.sound": "description.noise"}}); etc. ;) – iska Oct 18 '21 at 23:39
  • Yeah, the problem is that I cannot predict where the key to replace will be in terms of nesting and I have to run it on a 20GB db – fuzzKitty Oct 19 '21 at 10:06

0 Answers0