How do I know that UpdateOneAsync failed (from UpdateResult)?How do I calculate someone's age in C#?How do you give a C# Auto-Property a default value?How do I enumerate an enum in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I update the GUI from another thread?Get int value from enum in C#How do I generate a random int number?How to query MongoDB with “like”?What is a NullReferenceException, and how do I fix it?How do I drop a MongoDB database from the command line?

Examples of fluid (including air) being used to transmit digital data?

Is this car delivery via Ebay Motors on Craigslist a scam?

Possibility to correct pitch from digital versions of records with the hole not centered

Is there a minimum amount of electricity that can be fed back into the grid?

Why would "dead languages" be the only languages that spells could be written in?

Machine Learning Golf: Multiplication

How do amateur satellites stay consistently in the amateur-sat bands acoss the globe?

What do I need to see before Spider-Man: Far From Home?

Wearing special clothes in public while in niddah- isn't this a lack of tznius?

When moving a unique_ptr into a lambda, why is it not possible to call reset?

When is one 'Ready' to make Original Contributions to Mathematics?

How to find the version of extensions used on a Joomla website without access to the backend?

What's the difference between a type and a kind?

Do Goblin tokens count as Goblins?

How to get the speed of my spaceship?

How to play a D major chord lower than the open E major chord on guitar?

How complicated can a finite double complex over a field be?

Initializing variables in an "if" statement

Is reasonable to assume that the 食 in 月食/日食 can be interpreted as the sun/moon being "eaten" during an eclipse?

How many Jimmys can fit?

Multi-user CRUD: Valid, Problem, or Error?

I'm feeling like my character doesn't fit the campaign

Is there an upper limit on the number of cards a character can declare to draw from the Deck of Many Things?

Why does this function pointer assignment work when assigned directly but not with the conditional operator?



How do I know that UpdateOneAsync failed (from UpdateResult)?


How do I calculate someone's age in C#?How do you give a C# Auto-Property a default value?How do I enumerate an enum in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I update the GUI from another thread?Get int value from enum in C#How do I generate a random int number?How to query MongoDB with “like”?What is a NullReferenceException, and how do I fix it?How do I drop a MongoDB database from the command line?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to upsert one document into MongoDb. Pretty straightforward but what do I check (beyond the presence of an exception) to know that it failed?



Code:



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;




And then the code that calls it:



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);



It looked very simple (just look for the exception) until I saw UpdateResult. With not much context about what to do with it:



http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm



So even if I don't get an exception could it still have failed? I'm guessing if IsAcknowledged is false then I have failed. Is there a case where failure could have occured when IsAcknowledged is true?










share|improve this question






















  • The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

    – Neil Lunn
    Mar 26 at 7:47











  • Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

    – Neil Lunn
    Mar 26 at 7:50

















0















I'm trying to upsert one document into MongoDb. Pretty straightforward but what do I check (beyond the presence of an exception) to know that it failed?



Code:



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;




And then the code that calls it:



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);



It looked very simple (just look for the exception) until I saw UpdateResult. With not much context about what to do with it:



http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm



So even if I don't get an exception could it still have failed? I'm guessing if IsAcknowledged is false then I have failed. Is there a case where failure could have occured when IsAcknowledged is true?










share|improve this question






















  • The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

    – Neil Lunn
    Mar 26 at 7:47











  • Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

    – Neil Lunn
    Mar 26 at 7:50













0












0








0








I'm trying to upsert one document into MongoDb. Pretty straightforward but what do I check (beyond the presence of an exception) to know that it failed?



Code:



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;




And then the code that calls it:



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);



It looked very simple (just look for the exception) until I saw UpdateResult. With not much context about what to do with it:



http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm



So even if I don't get an exception could it still have failed? I'm guessing if IsAcknowledged is false then I have failed. Is there a case where failure could have occured when IsAcknowledged is true?










share|improve this question














I'm trying to upsert one document into MongoDb. Pretty straightforward but what do I check (beyond the presence of an exception) to know that it failed?



Code:



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;




And then the code that calls it:



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);



It looked very simple (just look for the exception) until I saw UpdateResult. With not much context about what to do with it:



http://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_UpdateResult.htm



So even if I don't get an exception could it still have failed? I'm guessing if IsAcknowledged is false then I have failed. Is there a case where failure could have occured when IsAcknowledged is true?







c# mongodb






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 20:40









Timothy John LairdTimothy John Laird

5812 gold badges7 silver badges15 bronze badges




5812 gold badges7 silver badges15 bronze badges












  • The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

    – Neil Lunn
    Mar 26 at 7:47











  • Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

    – Neil Lunn
    Mar 26 at 7:50

















  • The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

    – Neil Lunn
    Mar 26 at 7:47











  • Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

    – Neil Lunn
    Mar 26 at 7:50
















The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

– Neil Lunn
Mar 26 at 7:47





The point of UpdateResult is to tell you how many documents matched the expression you have and how many were modified as a result ( yes the same result class applies to multi document updates as well ). These numbers can differ considering that there are various conditions where a specified update may not result in any data actually being changed. Even in the case where nothing is matched this is not an error. An error is when something really bad happened. This might be a "network error", or it might be you tried to do something illegal.

– Neil Lunn
Mar 26 at 7:47













Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

– Neil Lunn
Mar 26 at 7:50





Errors of course are raised exceptions. So really you should always be looking at both. 1. The "update result" in order to see you actual matched and possiblly modified what you expected. 2. The "thrown errors" because that is when something actually was an exception. Not matching a document or modifying nothing is simply not an exception. Nor should it be. Your code is responsible for checking things worked as you expected them to.

– Neil Lunn
Mar 26 at 7:50












0






active

oldest

votes










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346087%2fhow-do-i-know-that-updateoneasync-failed-from-updateresult%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes




Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346087%2fhow-do-i-know-that-updateoneasync-failed-from-updateresult%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript