using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; var client = new MongoClient("mongodb://localhost:27017"); var db = client.GetDatabase("test"); var coll = db.GetCollection("update_with_aggregation_pipeline"); var doc = new MyDocument(); var filter = Builders.Filter.Eq(x => x.Id, doc.Id); var pipelineError = new EmptyPipelineDefinition() .Set(x => new MyDocument() { ValueObject = new() { Value = x.ValueObject == null ? 1 : x.ValueObject.Value + 1 } }); var updateError = Builders.Update.Pipeline(pipelineError); await coll.UpdateOneAsync(filter, updateError, new() { IsUpsert = true }); await PrintDocumentAsync(coll, doc.Id); await coll.UpdateOneAsync(filter, updateError, new() { IsUpsert = true }); await PrintDocumentAsync(coll, doc.Id); await coll.UpdateOneAsync(filter, updateError, new() { IsUpsert = true }); await PrintDocumentAsync(coll, doc.Id); async Task PrintDocumentAsync(IMongoCollection coll, string id) { var filter = Builders.Filter.Eq(x => x.Id, id); var doc = await (await coll.FindAsync(filter)).SingleOrDefaultAsync(); Console.WriteLine(doc.ValueObject?.Value); } class MyDocument { [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)] public string Id { get; set; } = ObjectId.GenerateNewId().ToString(); public MyValue ValueObject { get; set; } } class MyValue { public int Value { get; set; } } // Doesn't work too //var pipelineWithInitialization = new EmptyPipelineDefinition() // .Set(x => new MyDocument() // { // ValueObject = x.ValueObject ?? new() // }) // .Set(x => new MyDocument() // { // ValueObject = new() // { // Value = x.ValueObject.Value + 1 // } // }); //var updateWithInitialization = Builders.Update.Pipeline(pipelineWithInitialization); // A pipeline with static values works //var pipelineWorks = new EmptyPipelineDefinition() // .Set(x => new MyDocument() // { // ValueObject = new() // { // Value = 123 // } // });