Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6357033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T23:05:12+00:00 2026-05-24T23:05:12+00:00

I’m doing refactoring on production database and need to make some renamings. Version of

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T23:05:12+00:00Added an answer on May 24, 2026 at 11:05 pm

    I have implemented special type to do renaming of arbitrary field in MongoDB. Here is it:

    using System.Linq;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace DatabaseManagementTools
    {
        public class MongoDbRefactorer
        {
            protected MongoDatabase MongoDatabase { get; set; }
    
            public MongoDbRefactorer(MongoDatabase mongoDatabase)
            {
                MongoDatabase = mongoDatabase;
            }
    
            /// <summary>
            /// Renames field
            /// </summary>
            /// <param name="collectionName"></param>
            /// <param name="oldFieldNamePath">Supports nested types, even in array. Separate nest level with '$': "FooField1$FooFieldNested$FooFieldNestedNested"</param>
            /// <param name="newFieldName">Specify only field name without path to it: "NewFieldName", but not "FooField1$NewFieldName"</param>
            public void RenameField(string collectionName, string oldFieldNamePath, string newFieldName)
            {
                MongoCollection<BsonDocument> mongoCollection = MongoDatabase.GetCollection(collectionName);
                MongoCursor<BsonDocument> collectionCursor = mongoCollection.FindAll();
    
                PathSegments pathSegments = new PathSegments(oldFieldNamePath);
    
                // Rename field in each document of collection
                foreach (BsonDocument document in collectionCursor)
                {
                    int currentSegmentIndex = 0;
                    RenameField(document, pathSegments, currentSegmentIndex, newFieldName);
    
                    // Now document is modified in memory - replace old document with new in mongo:
                    mongoCollection.Save(document);
                }
            }
    
            private void RenameField(BsonValue bsonValue, PathSegments pathSegments, int currentSegmentIndex, string newFieldName)
            {
                string currentSegmentName = pathSegments[currentSegmentIndex];
    
                if (bsonValue.IsBsonArray)
                {
                    var array = bsonValue.AsBsonArray;
                    foreach (var arrayElement in array)
                    {
                        RenameField(arrayElement.AsBsonDocument, pathSegments, currentSegmentIndex, newFieldName);
                    }
                    return;
                }
    
                bool isLastNameSegment = pathSegments.Count() == currentSegmentIndex + 1;
                if (isLastNameSegment)
                {
                    RenameDirect(bsonValue, currentSegmentName, newFieldName);
                    return;
                }
    
                var innerDocument = bsonValue.AsBsonDocument[currentSegmentName];
                RenameField(innerDocument, pathSegments, currentSegmentIndex + 1, newFieldName);
            }
    
            private void RenameDirect(BsonValue document, string from, string to)
            {
                BsonElement bsonValue;
                bool elementFound = document.AsBsonDocument.TryGetElement(from, out bsonValue);
                if (elementFound)
                {
                    document.AsBsonDocument.Add(to, bsonValue.Value);
                    document.AsBsonDocument.Remove(from);
                }
                else
                {
                    // todo: log missing elements
                }
            }
        }
    }
    

    And helper type to keep path segments:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace DatabaseManagementTools
    {
        public class PathSegments : IEnumerable<string>
        {
            private List<string> Segments { get; set; }
    
            /// <summary>
            /// Split segment levels with '$'. For example: "School$CustomCodes"
            /// </summary>
            /// <param name="pathToParse"></param>
            public PathSegments(string pathToParse)
            {
                Segments = ParseSegments(pathToParse);
            }
    
            private static List<string> ParseSegments(string oldFieldNamePath)
            {
                string[] pathSegments = oldFieldNamePath.Trim(new []{'$', ' '})
                    .Split(new [] {'$'}, StringSplitOptions.RemoveEmptyEntries);
    
                return pathSegments.ToList();
            }
    
            public IEnumerator<string> GetEnumerator()
            {
                return Segments.GetEnumerator();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
    
            public string this[int index]
            {
                get { return Segments[index]; }
            }
        }
    }
    

    To separate nest levels I use ‘$’ sign – the only sign that is forbidden for collection names in mongo.
    Usage can be something like this:

    MongoDbRefactorer mongoDbRefactorer = new MongoDbRefactorer(Mongo.Database);
    mongoDbRefactorer.RenameField("schools", "FoobarTypesCustom$FoobarDefaultName", "FoobarName");
    

    This code will find in collection schools FoobarTypesCustom property. It can be as complex type so array. Then will find all FoobarDefaultName properties (if FoobarTypesCustom is array then it will iterate through it) and rename it to FoobarName. Nesting levels and number of nested arrays no matters.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have some data like this: 1 2 3 4 5 9 2 6
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I am trying to loop through a bunch of documents I have to put
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a bunch of posts stored in text files formatted in yaml/textile (from
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I need to clean up various Word 'smart' characters in user input, including but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.