MongoDB update: how to check if an update succeeds or fails?
I'm working with MongoDB in PHP using the pecl driver. My updates are working great, but I'd like to build some error checking into my function(s).
I've tried using lastError() in a pretty simple function:
function system_db_update_object($query, $values, $database, $collection) {
$connection = new Mongo();
$collection = $connection->$database->$collection;
$connection->$database->resetError(); //Added for debugging
$collection->update(
$query,
array('$set' => $values));
//$errorArray = $connection->$database->lastError();
var_dump($connection->$database->lastError());exit; // Var dump and /Exit/
}
But pretty much regardless of what I try to update (whether it exists or not) I get these same basic results:
array(4) {
["err"]=>
NULL
["updatedExisting"]=>
bool(true)
["n"]=>
float(1)
["ok"]=>
float(1)
}
开发者_运维技巧How do I know if the update succeeds or failed?
the "n" field is the number of documents that were updated, and "updatedExisting" tells whether any document was updated at all. you should be able to check those fields to see whether an update succeeded or not.
How do you know what rows are affected with a MongoDB update?
As with all write operations, getLastError
command in MongoDB can confirm the result of the update's write operation, described here:
http://docs.mongodb.org/manual/applications/update/
The getLastError
command returns the error status of the last operation on the current connection. By default MongoDB does not provide a response to confirm the success or failure of a write operation, clients typically use getLastError in combination with write operations to ensure that the write succeeds.
http://docs.mongodb.org/manual/reference/command/getLastError/#getLastError
精彩评论