MongoDB transaction

元气小坏坏 提交于 2019-12-12 20:56:31

问题


I have a method like below in C#:

private void Save(object)
{
   mongoCollection.Save(object);
   someotherRelationaldb.Save(object);
}

I have two DBs in which I have to save a object. One is MongoDB and another is a relational DB SQL server. If the Commit on Relational DB fails, I want to rollback the MongoDB save (I would like to maintain the order of save). What would be the proper way to rollback using the C# driver.


回答1:


Yes,

Now possible.

For example Java;

try (ClientSession clientSession = client.startSession()) {
   clientSession.startTransaction();
   collection.insertOne(clientSession, docOne);
   collection.insertOne(clientSession, docTwo);
   clientSession.commitTransaction();
}

See more about mongodb transactions




回答2:


You can't.
The only way to do this would be to wrap someotherRelationaldb.Save(object); in a try catch, and on the catch, do mongoCollection.Remove

You'd probably need a known identifier property on object and could then do something like:

mongoCollection.Remove(Query.EQ("_id", object.Id));

So, rather untidily, your Save method would look a bit like:

private void Save(object)
{
   mongoCollection.Save(object);

   try
   {
      someotherRelationaldb.Save(object);
   }
   catch
   {
      mongoCollection.Remove(Query.EQ("_id", object.Id));
   }
}

Another way is to store a flag property on the object that get's updated after the successful write to someOtherRelationaldb

This isn't exactly ideal either, but you could modify your query to only return docs where IsPersisted flag is true.

Neither of these approaches will play nice in a heavily sharded environment though I wouldn't think.



来源:https://stackoverflow.com/questions/14161042/mongodb-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!