jmt
jmt

Reputation: 97

Mongo C# - update single field, if not insert document

I'm using the C# Mongo driver v2.9.2 in a small project of mine and I'm trying to figure out how I can do an upsert that only updates a single field if a document exists, and if not inserts the entire document.

I have the following POCO class representing the document:

public class Event 
{
    public Guid EventId { get; set;}
    public DateTime ReceivedAt { get; set;}
    public string Body { get; set; }
}

If my code receives an event that it's already seen (based on the EventId) I want to only update the Body field and maintain the original value of ReceivedAt / EventId. If it can't find a match for the document based on EventId I want the document to be inserted.

Currently I'm using ReplaceOneModel<Event> however this updates all fields when upserting:

var model = events.Select(
    e => new ReplaceOneModel<Event>(Builders<Event>.Filter.Where(
        x => x.EventId == e.EventId), e) { IsUpsert = true });

await collection.BulkWriteAsync(model);

Any help is much appreciated!

Upvotes: 1

Views: 686

Answers (1)

Mahdi
Mahdi

Reputation: 3349

You can do it like this:

var filter = Builders<MyEvent>.Filter.Eq(x => x.Id, id);
var update = Builders<MyEvent>.Update
    .Set(x => x.Body, "a new event body");
await context.MyCollection.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true });

Upvotes: 1

Related Questions