執行effcient UPSERT我有以下C#模型類:MongoDB中
public class Thingy
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public DateTime TimeCreated { get; set; }
public string Content { get; set; }
public string UUID { get; set; }
}
和以下ASP.MVC控制器動作:
public ActionResult Create(Thingy thing)
{
var query = Query.EQ("UUID", thing.UUID);
var update = Update.Set("Title", thing.Title)
.Set("Content", thing.Content);
var t = _collection.Update(query, update, SafeMode.True);
if (t.UpdatedExisting == false)
{
thing.TimeCreated = DateTime.Now;
thing.UUID = System.Guid.NewGuid().ToString();
_collection.Insert(thing);
}
/*
var t = _collection.FindOne(query);
if (t == null)
{
thing.TimeCreated = DateTime.Now;
thing.UUID = System.Guid.NewGuid().ToString();
_collection.Insert(thing);
}
else
{
_collection.Update(query, update);
}
*/
return RedirectToAction("Index", "Home");
}
此方法要麼不更新或插入。如果需要執行插入操作,則必須設置UUID和TimeCreated成員。如果需要更新,則必須單獨保留UUID和TimeCreated,但必須更新成員標題和內容。
被註釋掉的代碼有效,但似乎不是最有效的。當它調用FindOne時,這是一次mongodb之旅。然後,如果它轉到else子句,它會執行另一個查詢和更新操作,所以這是mongodb的另外兩次訪問。
什麼是更有效的方法來做我想要完成的事情?
見做upserts時蒙戈[1]在C#MongoDB的upsertting信息採取這種做法。 [1]:http://stackoverflow.com/questions/7240028/upserting-in-mongo-db-using-official-c-sharp-driver – slee
@slee:是的,我看到了和其他來自mongodb網站的參考資料/教程。請重新閱讀我的問題。 –
Mongo徹底改變了他所做的2個dll發佈之間的界面:S – Revious