skip to Main Content

I want to be able copy one field to another in a UpdateMany statement.

Something like this:

var updateDef = MongoDB.Driver.Builders<UserStory>
    .Update
    .Set(x => x.SemanticId, x => x.Id);

But the current API doesn’t support that.

How can I do something similar with the Csharp driver, i.e., copy a field to another for all documents in the collection? I also need to get an ObjectId generated in a new field.

2

Answers


  1. Chosen as BEST ANSWER

    Can't be done with the correct collection type, from what I've found..

    Must use BsonDocument:

    var collection = _mongo.GetCollection<BsonDocument>("SomCollection");
    var updateDefinition = Builders<BsonDocument>.Update.Set("someField", "$otherField");
    var result = collection.UpdateMany(FilterDefinition<BsonDocument>.Empty, updateDefinition);
    

  2. Close to what @jgauffin provided above, but a bit more good looking:

            var client = new MongoClient();
            var db = client.GetDatabase("db");
            var collection = db.GetCollection<Entity>("coll");
            collection.InsertOne(new Entity() { SomeField = "sf", otherFields = "of"});
            var pipeline = new EmptyPipelineDefinition<Entity>()
                .AppendStage<Entity, Entity, Entity>(
                    new BsonDocument
                    {
                        { "$set", new BsonDocument(nameof(Entity.SomeField), $"${nameof(Entity.OtherFields)}") }
                    });
            var rendered = pipeline.Render(BsonSerializer.SerializerRegistry.GetSerializer<Entity>(), BsonSerializer.SerializerRegistry);
            var updated = collection.UpdateMany(FilterDefinition<Entity>.Empty, pipeline);
            var result = collection.Find("{}").ToList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search