I’m doing refactoring on production database and need to make some renamings. Version of mongodb is 1.8.0. I use C# driver to do refactoring of database. Have faced with problem when I try to rename field of complex type that is located in array.
For example I have such document:
FoobarCollection:
{
Field1: "",
Field2: [
{ NestedField1: "", NestedField2: "" },
{ NestedField1: "", NestedField2: "" },
...
]
}
I Need to rename NestedField2 into NestedField3, for example.
MongoDB documentation says:
$rename
Version 1.7.2+ only.
{ $rename : { old_field_name : new_field_name } }
Renames the field with name ‘old_field_name’ to ‘new_field_name’. Does not expand arrays to find a match for ‘old_field_name’.
As I understand, simply using Update.Rename() wouldn’t give result, because as documentation says “rename – doesn’t expand arrays to find a match for old field name”
What C# code I should write to rename NestedField2 into NestedField3?
I have implemented special type to do renaming of arbitrary field in MongoDB. Here is it:
And helper type to keep path segments:
To separate nest levels I use ‘$’ sign – the only sign that is forbidden for collection names in mongo.
Usage can be something like this:
This code will find in collection
schoolsFoobarTypesCustomproperty. It can be as complex type so array. Then will find allFoobarDefaultNameproperties (ifFoobarTypesCustomis array then it will iterate through it) and rename it toFoobarName. Nesting levels and number of nested arrays no matters.