开发者

How to get affected number of rows using mongodb ,php driver

I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? 开发者_如何学JAVAthanks .


You can get number of results right from the cursor using count function:

$collection->find()->count();

You can even get number of all records in collection using:

$collection->count();

Using insert method, _id is added to input array automatically.

$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);

array(2) {
  ["x"]=>
    int(1)
  ["_id"]=>
    object(MongoId)#4 (0) {
    }
  }


I don't believe that there is any type of affected_rows() method at your disposal with mongodb. As for the last insert _id You can generate them in your application code and include them in your insert, so there's really no need for any mysql like insert_id() method.

$id = new MongoId();
$collection->insert(array('
    '_id' => $id,
    'username' => 'username',
    'email' => 'johndoe@gmail.com'
'));

Now you can use the object stored in $id however you wish.


Maybe MongoDB::lastError is what you are looking for: (http://php.net/manual/en/mongodb.lasterror.php)

It calls the getLastError command: (http://www.mongodb.org/display/DOCS/getLastError+Command)

which returns, among other things:

n - if an update was done, this is the number of documents updated.


For number of affected rows:

        $status = $collection->update( $criteria, array( '$set' => $data ) );
        $status['n']; // 'n' is the number of affected rows


If you have the output of your action, you can call relative function:

//        $m hold mongo library object
$output    = $m->myCollection->updateOne([
    '_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
    '$set' => ['column' => 'value']
]);
// get number of modified records
$count     = $output->getModifiedCount();

$output is of of type MongoDB\UpdateResult. Relatively check following files to figure out the best function to find inserted, deleted, matched or whatever result you need:

  • 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜