问题
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