C# Insert if not exists for big object, without update if exists

hello how i can atomic do action like: insert if not exists without update if exists for object with example 100 fields ?

I try

  1. Replace method with upsert , but it update fields if exists.
  2. I found solution like update+$setOnInsert but this method require field (not ready object) and i take 50 line code :smiley:
    example on insert i need only 50 fields,

  var newObject = new
        {
            a = 'asdas',
            b = 'fdsd',
            c = 'ngasdas',
}


Update ( findById
Builders<C>.Update.SetOnInsert(c => c.a, newObject.a);
Builders<C>.Update.SetOnInsert(c => c.b, newObject.b);
Builders<C>.Update.SetOnInsert(c => c.c, newObject.c);
........... more 47 lines....
,upsert = true)

is there a better solution than this?

1 Like

You can use a BsonDocument to write an UpdateDefinition directly and serialize the target object to another BsonDocument.

var result = await _collection.UpdateOneAsync(
    findById,
    new BsonDocument("$setOnInsert", newObject.ToBsonDocument()),
    new() { IsUpsert = true });
1 Like