Upserting in Mongo DB using official C# driver

后端 未结 4 753
别跟我提以往
别跟我提以往 2020-12-04 18:04

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(cam         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-04 18:18

    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.

提交回复
热议问题