Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? thanks .

like image 854
renenglish Avatar asked Mar 17 '11 01:03

renenglish


People also ask

How to fetch data from MongoDB using PHP?

php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->mycol; echo "Collection selected succsessfully"; // now update the document $collection->update(array("title"=>"MongoDB"), array('$set'=> ...

What is MongoDB PHP driver?

MongoDB driver ¶It provides a minimal API for core driver functionality: commands, queries, writes, connection management, and BSON serialization. Userland PHP libraries that depend on this extension may provide higher level APIs, such as query builders, individual command helper methods, and GridFS.

Can I use PHP with MongoDB?

You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

How to insert data in MongoDB in PHP?

$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three']; $_id1 = $bulk->insert($document1); $_id2 = $bulk->insert($document2); $_id3 = $bulk->insert($document3);


2 Answers

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) {
    }
  }
like image 86
jhavrda Avatar answered Oct 19 '22 08:10

jhavrda


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' => '[email protected]'
'));

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

like image 41
Anthony Jack Avatar answered Oct 19 '22 08:10

Anthony Jack