-1

I have following document:

{

   "dataset_path":"path_of_dataset",

   "project_1":{

      "model_1":"path_of_model_1",

      "model_2":"path_of_model_2"

   }

}

I want to change "project_1" to "renamed_project_1" and "path_of_model_1" to "new_model_1_path". The resultant output should be as follows:

{

   "dataset_path":"path_of_dataset",

   "renamed_project_1":{

      "renamed_model_1":"new_model_1_path",

      "model_2":"path_of_model_2"

   }

}

Here is what I tried:

db.collection.update_many({'dataset_path': 'path_to_dataset'}, {'$rename': {"project_1": "renamed_project_1"}},
                          {'$set': {"project_1.model_1": "new_model_1_path"}})

but the above query throws following error:

pymongo.errors.WriteError: Updating the path X would create a conflict at X.

Muhammad Hassan
  • 4,079
  • 1
  • 13
  • 27

2 Answers2

0

That's because you're trying to mutate project_1 field two times in a single query. Mongo just doesn't know how to deal with that. You should consider splitting two operations:

db.collection.update_many({'dataset_path': 'path_to_dataset'}, {'$rename': {"project_1": "renamed_project_1"}})
db.collection.update_many({'dataset_path': 'path_to_dataset'}, {'$set': {"renamed_project_1.model_1": "new_model_1_path"}})
sur0k
  • 334
  • 1
  • 6
  • As an addition, I don't believe it is possible using a single query. That sounds weird to me. – sur0k Mar 10 '21 at 20:29
0
db.collection.update_many({}, {"$rename": {"old_value": "new_value"}})
zeroalpha
  • 173
  • 1
  • 11