At the moment i'm updating the entire document, but if the ID changes i get error message:
MongoDB.Driver.MongoWriteException: 'A write operation resulted in an error. After applying the update, the (immutable) field '_id' was found to have been altered to _id: BinData(3, B3FD0EE0FF161845BE96BE40A7DDE84B)'
So i want it to ignore the ID field when updating a document.
Here's what i'm doing now:
public async Task<bool> UpdateMatch(Guid id, Match match)
{
ReplaceOneResult actionResult
= await _context.Match.ReplaceOneAsync(m => m.Id.Equals(id),
match,
new UpdateOptions { IsUpsert = true });
return actionResult.IsAcknowledged && actionResult.ModifiedCount > 0;
}
Thanks in advance for your help!
Add 'BsonIgnoreIfDefault' attribute to the InternalId property.
public class Document
{
[BsonId]
[BsonIgnoreIfDefault]
public ObjectId InternalId { get; set; }
// rest of document
}
The problem which is happening is that MongoDB will add the _id field to the replacement document if it is not specified in either the filter or replacement documents if ReplaceOneAsync is used. If _id is present in both, the values must be equal. However, if I understand your code properly you are trying to find a document by ID and replace it. There is a collection method called FindOneAndReplace() or FindOneAndReplaceAsync() that I would have used if I were you. You might want to check out the MongoDB documentation for this:
https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/
https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/
Hope this helps you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With