Search code examples
c#mongodbmongodb-.net-driver

Upserting in Mongo DB using official C# driver


In the official documentation of mongodb they mention upserts, so it would be really nice to write an upsert command instead of:

if (_campaignRepo.Exists(camp))
{
    _campaignRepo.DeleteByIdAndSystemId(camp);
}

_campaignRepo.Save(camp);

something which would implement that logic on the db level if it is possible. So what is the way to do an upsert if there is one?


Solution

  • The following code is from a working app:

    weekplanStore.Update(
        Query.EQ("weekNumber", week),
        Update.Replace(rawWeekPlan),
        UpdateFlags.Upsert);
    

    The weekplanStore is my MongoDB collection, and the code will update the document found with the query in the first argument or insert a new one if none is found. The "trick" is to use the UpdateFlags.Upsert modifier.

    The rawWeekPlan is the object inserted or updated, and has the following type:

    private class RawWeekPlan
    {
        public ObjectId id;
        public int weekNumber;
        public WeekPlanEntry[] entries;
    }
    

    and turned into bson by the driver automatically.