Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update entire document except ID with mongodb c# driver

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!

like image 204
user10384441 Avatar asked Oct 02 '18 11:10

user10384441


2 Answers

Add 'BsonIgnoreIfDefault' attribute to the InternalId property.

public class Document
{
    [BsonId]       
    [BsonIgnoreIfDefault]
    public ObjectId InternalId { get; set; }
    // rest of document
}
like image 197
Damien Avatar answered Nov 05 '22 16:11

Damien


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!

like image 2
Zen Avatar answered Nov 05 '22 15:11

Zen