Originally posted at: MongoDB C# Driver - Conditional `UpdateDefinition`? - Stack Overflow
What is the simpler way of doing this?
// var request = ...
var result = MyDbCollection.UpdateOneAsync(
a => otherConditions && a.MyObject != null,
Builders<MyDocument>.Update
.Set(a => a.MyObject!.A, request.A)
.Set(a => a.MyObject!.B, request.B)
.Set(a => a.MyObject!.C, request.C));
if (result.ModifiedCount <= 0)
{
MyDbCollection.UpdateOneAsync(
a => otherConditions && a.MyObject == null,
Builders<MyDocument>.Update
.Set(a => a.MyObject, new MyDocument.MyObject()
{
A = request.A,
B = request.B,
C = request.C
}));
}
Notice the differing a.MyObject != null
and a.MyObject == null
conditions, ideally I want to do something like in this pseudocode:
MyDbCollection.UpdateOneAsync(
a => otherConditions
Builders<MyDocument>.Update
.Condition(a => a.MyObject != null)
.Then(builder => builder
.Set(a => a.MyObject!.A, request.A)
.Set(a => a.MyObject!.B, request.B)
.Set(a => a.MyObject!.C, request.C)
)
.Else(builder => builder
.Set(a => a.MyObject, new MyDocument.MyObject()
{
A = request.A,
B = request.B,
C = request.C
})
)
I’ve wasted hours at this point trying to do it with aggregation pipelines where I keep getting this error:
System.InvalidCastException:
Unable to cast object of type 'MongoDB.Bson.BsonArray' to type 'MongoDB.Bson.BsonDocument'.
I don’t have that code anymore so I can’t copy paste it here. Sorry!