Today, the wind is blowing outside. It is also a pleasure to write a blog in a warm hut. Well, let's talk a little bit about it. Today we will talk about how to connect to and operate mongodb using php. If you haven't followed the two phases, if you do not know how to install php extensions for mongodb, please go back to see Mongodb and Mongodb.
Php connection to mongodb
try { $mongo = new Mongo("mongodb://username:password@127.0.0.1:27017/db1");}catch(MongoConnectionException $e) { print $e->getMessage(); exit;}
Select Database blog
$db = $mongo->blog;
Close Database
$conn->close();
Select Operation set
$collection = $db->users;
Insert data
$user = array('name' => 'caleng', 'city' => 'beijing');$collection->insert($user);
Modify data
$newdata = array('$set' => array("city" => "shanghai"));$collection->update(array("name" => "caleng"), $newdata);
Delete data
$collection->remove(array('name'=>'caleng'), array("justOne" => true));
Search for Data
Search for a piece of data
$result= $collection->findone(array("name"=>"caleng"));
Query a list
// Find the data created at a time later than $ start = 1; $ counditionarray = array ("ctime" => array ('$ gt' => 1337184000 )); $ list_data = $ this-> game_handle-> find ($ counditionarray); $ total = $ this-> game_handle-> count ($ counditionarray ); $ list_data-> limit ($ count); // data end position $ list_data-> skip ($ start); // the position where the data starts to be retrieved var_dump ($ list_data );
In Query
$cursor = $collection->find(array( 'name' => array('$in' => array('Joe', 'Wendy'))));
Group Query
$collection->insert(array("category" => "fruit", "name" => "apple"));$collection->insert(array("category" => "fruit", "name" => "peach"));$collection->insert(array("category" => "fruit", "name" => "banana"));$collection->insert(array("category" => "veggie", "name" => "corn"));$collection->insert(array("category" => "veggie", "name" => "broccoli"));$keys = array("category" => 1);$initial = array("items" => array());$reduce = "function (obj, prev) { prev.items.push(obj.name); }";$g = $collection->group($keys, $initial, $reduce);echo json_encode($g['retval']);
Output result:
[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]
The result is a two-dimensional array.
array( 0 => array("category" =>"fruit", "items"=>array("apple","peach","banana")), 1 => array("category" =>"veggie", "items"=>array("corn","broccoli")))
Here we have written some simple operations. If you want to use php to better serve mongodb, read the manual.
Address sent: http://cn2.php.net/manual/zh/class.mongocollection.php
Now, Mongodb is written here. I think you will be more and more familiar with the future.
I used Zhang Yusheng's "I look forward" to share with you "say goodbye! "