我正在尝试将一个文档插入到MongoDb中。很简单,但是我要检查(除了异常以外)知道失败了吗?
代码:
public async Task<UpdateResult> UpdateDocument<T>(
string sConnectionString,
string sDatabaseName,
string sCollectionName,
Expression<Func<T, bool>> filter,
UpdateDefinition<T> update,
bool bUpsert,
System.Threading.CancellationToken cancellationToken
)
{
ConnectToDb(sConnectionString);
IMongoDatabase db = _mongoClient.GetDatabase(sDatabaseName);
IMongoCollection<T> collection = db.GetCollection<T>(sCollectionName);
return await collection.UpdateOneAsync<T>(filter, update, new UpdateOptions() { IsUpsert = bUpsert }, cancellationToken);
}
private void ConnectToDb(
string sConnectionString
)
{
if(sConnectionString != _sConnectionString)
{
_mongoClient = null;
_mongoClient = new MongoClient(sConnectionString);
_sConnectionString = sConnectionString;
}
}
然后是调用它的代码:
try
{
MongoDB.Driver.UpdateResult updateResult = await _db.UpdateDocument<Models.NodeBoardModel>(
_dbSettings._sURLMongoDbConnectionString,
_dbSettings._sDatabasename, Constants.NodeBoardCollectionName,
node => node.Id == boardToServerData._request.Id,
MongoDB.Driver.Builders<Models.NodeBoardModel>.Update.Set(node => node.RemoteBoard, dbboardmodel),
true,
stoppingToken
);
bool bAcked = updateResult.IsAcknowledged;
if(updateResult.
}
catch(AggregateException aggEx)
{
Models.Errors errors = null;
errors = Helpers.ProcessAggregateException(
aggEx,
Models.eError.UPSERTREMOTEBOARD
);
_logger.LogError(errors.GetErrorModel()._sSpecificErrorMessage);
}
catch(Exception ex)
{
Models.Errors errors = null;
errors = Helpers.ProcessException(
ex,
Models.eError.UPSERTREMOTEBOARD
);
_logger.LogError(errors.GetErrorModel()._sSpecificErrorMessage);
}
在我看到UpdateResult之前,它看起来非常简单(只需查找异常)。没有太多关于如何处理的上下文:
http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm
所以即使我没有遇到异常,它是否仍然会失败?我猜如果IsAcknowledged为假,那么我失败了。如果IsAcknowledged为true,是否有可能发生故障?