Hi!
I recently came across some odd behaviour during an upsert while using FindOneAndUpdateAsync
.
For some reason, the BsonType of a string
property with null
value is being converted from BsonNull
to BsonString
and, consequently, the property is being saved with the value of BsonNull
, instead of null
!
The core logic is similar to the below snippet
async Task FindOneAndUpdateAsync<T>(T document, FilterDefinition<T> filter = null)
{
var bsonDocument = document.ToBsonDocument();
if (filter == null)
{
var bsonValue = bsonDocument["_id"];
filter = Builders<T>.Filter.Eq("_id", bsonValue);
}
var propertiesToIgnore = new List<string> { "_t" };
if (bsonDocument.GetValue("_id", null) == null)
{
propertiesToIgnore.Add("_id");
}
var updates = bsonDocument
.Where(a => !propertiesToIgnore.Contains(a.Name))
.Select(a => Builders<T>.Update.Set(a.Name, a.Value));
await GetCollection<T>().FindOneAndUpdateAsync(
filter,
Builders<T>.Update.Combine(updates),
new FindOneAndUpdateOptions<T> { IsUpsert = true });
}
Is anyone able to shed some light into why this is happening?
Here is a link to the working example.
Thank you.