如何获取受影响的行数使用MongoDB,PHP驱动程序
答
您可以直接从游标使用count函数得到的结果数
$collection->count();
用插入法,_id是自动添加到输入数组。
$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
答
我不认为在MongoDB中有任何类型的affected_rows()方法供您使用。至于最后一个插入_id你可以在你的应用程序代码中生成它们并将它们包含在你的插入中,所以真的不需要像insert_id()方法那样的任何mysql。
$id = new MongoId();
$collection->insert(array('
'_id' => $id,
'username' => 'username',
'email' => '[email protected]'
'));
现在,您可以使用存储在$ id中的对象,但是您希望。
$collection->find()->count();
你甚至可以使用获得的集合中的所有记录数:
答
也许的MongoDB :: lastError是你在找什么: (http://php.net/manual/en/mongodb.lasterror.php)
它调用GetLastError函数命令: (http://www.mongodb.org/display/DOCS/getLastError+Command)
返回,其他中东西:
n - 如果更新完成,则这是已更新文档的数量。
答
对于受影响的行数:
$status = $collection->update($criteria, array('$set' => $data));
$status['n']; // 'n' is the number of affected rows
答
如果你有你的行动的输出,你可以调用相关功能:
// $m hold mongo library object
$output = $m->myCollection->updateOne([
'_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
'$set' => ['column' => 'value']
]);
// get number of modified records
$count = $output->getModifiedCount();
$输出是MongoDB\UpdateResult
类型。相对检查以下文件,以找出最佳的功能找到插入,删除,匹配或任何导致你需要:
- https://github.com/mongodb/mongo-php-library/blob/master/src/InsertManyResult.php
- https://github.com/mongodb/mongo-php-library/blob/master/src/DeleteResult.php
- https://github.com/mongodb/mongo-php-library/blob/master/src/InsertOneResult.php
- https://github.com/mongodb/mongo-php-library/blob/master/src/UpdateResult.php
+1只是这个答案返回受影响的行。 – PHPst 2012-12-18 18:12:34