Search code examples
mongodbmongodb-.net-driver

How to rename a document field of a nested array in mongodb in c#


given a collection with the following documents in MongoDB:

{
  id: guid,
  items: [
    {
      fieldA : "value"
      ...
    },
    {
      fieldA : "value"
      ...
    },
  ]
},
{  ...
}

I must to find an efficient way to rename fieldA to fieldB using C#. It seems to me that MongoDB does not provide a rename operator usable with arrays.

I tried the path to add a new field to the array, but I do not know how to set that field to the value of the old one.

Any help is appreciated. Thanks


Solution

  • There's no typesafe way of currently achieving this in MongoDB Driver 2.10.4. However, you can build up an aggregation pipeline with a $map and execute it as an update pipeline.

    
    var db = client.GetDatabase("test");
    var collection = db.GetCollection<MyClass>("data");
    
    var filter = Builders<MyClass>.Filter
        .Empty;
    
    var update = Builders<MyClass>.Update.Pipeline(
        new PipelineStagePipelineDefinition<MyClass, MyClass>(
            new PipelineStageDefinition<MyClass, MyClass>[]
            {
                @"{ ""$addFields"": {
                      items: {
                        $map: {
                          input: ""$items"",
                          as: ""item"",
                          in: {
                            fieldB: ""$$item.fieldA""
                          }
                        }
                      }
                    }
                  }"}));
    
    await collection.UpdateManyAsync(filter, update)
        .ConfigureAwait(false);
    

    This works by running the pipeline and updating each document with the output of the pipeline, the above is a simple pipeline that replaces the items field with a new items field with a new array mapped from the old array.