Adding a property that copies another property from the same document

I have an object like this:

public class MigrationObject: IIdItem
{
    public string Id { get; set; }

    public string Name { get; set; }
}

Now I’m adding a property Fqdn which should be a copy of the Name property:

public class MigrationObject: IIdItem
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Fqdn { get; set; }

}

Now I could either iterate through all documents, and calling collection.UpdateOne on each,

    foreach (var item in col.FindSync(filter).ToList())
    {
        var update = Builders<MigrationObject>.Update.Set(c => c.Fqdn, item.Name);
        col.UpdateOne(Builders<MigrationObject>.Filter.Eq(c => c.Id, item.Id), update);
    }

but that’s not a good approach since apparently there’s a way without having to load all the documents. I tried it with this

    var updatePipeline = "{{ '$set': {{ 'Fqdn': {{ '$Name' }} }} }}";
    var updateDoc = BsonDocument.Parse(updatePipeline);
    var res = col.UpdateMany(filter, updateDoc);

but this cannot be parsed. Any idea where I’m going wrong?

Found the solution after some additional searching

   var filter = Builders<MigrationObject>.Filter.Empty;
    var col = db.GetCollection<MigrationObject>(collectionName);
    var pipeline = new EmptyPipelineDefinition<MigrationObject>()
        .AppendStage<MigrationObject, MigrationObject, MigrationObject>("{ $set: { Fqdn: '$Name' } }");
    var update = Builders<MigrationObject>.Update.Pipeline(pipeline);
    var res = col.UpdateMany(filter, update);
1 Like

Thanks for sharing the solution you found. You may mark your post as the solution.

This is the best way to keep this forum useful.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.