Brian Var
Brian Var

Reputation: 6227

How to upsert a document in MongoDB .Net?

I'm adding an UpdateCustomer method that passes in the modified customer to be persisted to the DB. But I've come across an error when calling ReplaceOneAsync on the updated document.

I've consulted the following example and api reference, which both state to pass ReplaceOneAsync a filter and document parameters.

But the specific errors are thrown because of incorrect parameters, as stated below:

Error   1   The best overloaded method match for 'MongoDB.Driver.IMongoCollection<MongoDBApp.Models.CustomerModel>.ReplaceOneAsync(MongoDB.Driver.FilterDefinition<MongoDBApp.Models.CustomerModel>, MongoDBApp.Models.CustomerModel, MongoDB.Driver.UpdateOptions, System.Threading.CancellationToken)' has some invalid arguments 

Error   2   Argument 2: cannot convert from 'MongoDB.Bson.BsonDocument' to 'MongoDBApp.Models.CustomerModel'    

Anyone have any hints on making sense of the error?

The UpdateCustomer method:

public async Task UpdateCustomer(CustomerModel customer)
{          
    var collection = StartConnection();
    var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);

    BsonDocument doc = new BsonDocument();

    doc["_id"] = customer.Id;
    doc["firstName"] = customer.FirstName;
    doc["lastName"] = customer.LastName;
    doc["email"] = customer.Email;

    //error thrown here on the ReplaceOneAsync params..
    await collection.ReplaceOneAsync(filter, doc);           
}

And the associated StartConnection method:

private static IMongoCollection<CustomerModel> StartConnection()
{
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("orders");
    //Get a handle on the customers collection:
    var collection = database.GetCollection<CustomerModel>("customers");
    return collection;
}

Upvotes: 2

Views: 8073

Answers (2)

D__
D__

Reputation: 141

this works for me

var filter = Builders.Filter.Where(x => x.Id == customer.Id); await Collection.ReplaceOneAsync(filter, item, new ReplaceOptions { IsUpsert = true });

Upvotes: 1

i3arnon
i3arnon

Reputation: 116548

You need to use the typed collection all the way down which means inserting an instance of CustomerModel, not a BsonDocument:

await collection.ReplaceOneAsync(filter, customer);

Or use the untyped one with BsonDocument, but do that from the start:

var collection = database.GetCollection<BsonDocument>("customers");

You're getting these compiliation errors because you're mixing these two options.

Upvotes: 2

Related Questions