首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重命名位于数组中的复杂类型字段

重命名位于数组中的复杂类型字段
EN

Stack Overflow用户
提问于 2011-08-18 15:04:21
回答 1查看 2.2K关注 0票数 3

我正在对生产数据库进行重构,需要进行一些重命名。mongodb的版本为1.8.0。我使用C#驱动程序对数据库进行重构。当我试图重命名位于数组中的复杂类型字段时,遇到了问题。

例如,我有这样的文件:

代码语言:javascript
复制
FoobarCollection:

{
  Field1: "",
  Field2: [
    { NestedField1: "", NestedField2: "" },
    { NestedField1: "", NestedField2: "" },
    ... 
  ]
}

例如,我需要将NestedField2重命名为NestedField3。MongoDB文档说:

$rename

仅限1.7.2+版本。

{ $rename:{ old_field_name : new_field_name }将名为“old_field_name”的字段重命名为“new_ name”。不展开数组来查找“old_field_name”的匹配项。

据我所知,仅仅使用Update.Rename()不会给出结果,因为正如文档所述,"rename -不展开数组以找到与旧字段名匹配的值“。

我应该写什么C#代码来将NestedField2重命名为NestedField3

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-21 21:05:47

我在MongoDB中实现了对任意字段进行重命名的特殊类型。这就是:

代码语言:javascript
复制
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
            }
        }
    }
}

以及保持路径段的助手类型:

代码语言:javascript
复制
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]; }
        }
    }
}

为了区分巢级,我使用了“$”符号--芒果语中唯一禁止集合名称的符号。用法可以如下所示:

代码语言:javascript
复制
MongoDbRefactorer mongoDbRefactorer = new MongoDbRefactorer(Mongo.Database);
mongoDbRefactorer.RenameField("schools", "FoobarTypesCustom$FoobarDefaultName", "FoobarName");

此代码将在集合schools FoobarTypesCustom属性中找到。它可以是复杂类型的so数组。然后将找到所有FoobarDefaultName属性(如果FoobarTypesCustom是数组,那么它将遍历它)并将其重命名为FoobarName。嵌套级别和嵌套数组的数量无关紧要。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7109654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档