使用官方C#驱动程序在Mongo DB中进行升级 [英] Upserting in Mongo DB using official C# driver
问题描述
在mongodb的官方文档中,他们提到了upserts,因此编写upsert命令而不是:
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?
推荐答案
以下代码来自正在运行的应用程序:
The following code is from a working app:
weekplanStore.Update(
Query.EQ("weekNumber", week),
Update.Replace(rawWeekPlan),
UpdateFlags.Upsert);
weekplanStore是我的MongoDB集合,并且代码将更新在第一个参数中使用查询找到的文档,或者如果找不到则插入一个新的文档. 技巧"是使用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.
rawWeekPlan是插入或更新的对象,并且具有以下类型:
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;
}
并由驱动程序自动变成bson.
and turned into bson by the driver automatically.
这篇关于使用官方C#驱动程序在Mongo DB中进行升级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!