Using MongoDB and the latest 10gen C# driver (CSharpDriver-1.3.1.4349), I am trying to do an "in place" update and get back the # of documents effected in the result.
public static long SaveListings(string state, bool isActive, DateTime updateDate)
{
var result = Collection().Update(
Query.And(
Query.EQ("State", state),
Query.And(
Query.EQ("IsActive", isActive),
Query.LT("UpdateDate", updateDate))),
Update.Set("IsActive", false), UpdateFlags.Multi);
return result != null ? result.DocumentsAffected : -1;
}
The result is null for some reason. If I were doing this from the console, I could get the number of rows effected by doing this:
db.Listing.update( { State: state.Abbreviation, IsActive: true, UpdateDate: { $lt: expiredDate } }, { $set: { IsActive: false } }, false, true);
var numRows = db.getLastErrorObj().n;
Any idea what I'm doing wrong or is this a bug in the C# driver?
Update contains overloaded method that take SafeMode
. Just add it to your code as fourth parameter to your update and should be not null:
...
UpdateFlags.Multi,
SafeMode.True);
That's not driver bug, it work as expected. Mongodb does not wait for document if get inserted without safe mode (therefore driver return null), but if you saying SafeMode = true -- you force mongodb wait until document get inserted.
Doing inserts and updates without specifying safe mode yields null because they're asynchronous operations - there's simply no way to know how the insert or update went.
Therefore, add e.g. SafeMode.True as the last argument in inserts and updates in cases where you care about the result. This will make the driver issue a getLastError
command, which blocks until the insert/updated has completed:
var result = collection.Update(query, update, SafeMode.True);
You can read some more about getLastError
and different safe modes here (general) and here (SafeMode
with the C# driver).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With