How can I replace an object in mongodb without specifying a filter using the C# driver?

2.5k Views Asked by At

I am using the C# driver 2.0. I have a POCO that I am storing in mongo that looks like this:

public class TestObject
{
     [BsonId]
     public Guid Id { get; set; }
     public string Property1 { get; set; }
}

I am storing the object using a generic method like this:

public async void Insert<T>(T item)
{
        var collection = GetCollection<T>();

        await collection.InsertOneAsync(item);
}

I would like to have a similar method to Update an object. However, the ReplaceOneAsync method requires a filter be specified.

I would like to simply update the same object, based on whatever the [BsonId] property is. Any one know if this is possible?

1

There are 1 best solutions below

0
On

I completely agree with @i3arnon, typical solution is next:

interface for your models:

public interface IEntity
{
    string Id { get; set; }
}

save method in your base repository

public async Task SaveAsyn<T>(T entity) where T : IEntity
{
    var collection = GetCollection<T>();
    if (entity.Id == null)
    {
        await collection.InsertOneAsync(entity);
    }
    else
    {
        await collection.ReplaceOneAsync(x => x.Id == entity.Id, entity);
    }
}

And also about ID, you can continue using ID as Guid, but more robust and simpler solution is using string (explanation about Id).