There is a strong wind blowing outside today. Being able to write a blog in a warm hut is also a kind of happiness for Beidiao. Okay, without further ado, today I will mainly talk about PHP connection and operation of mongodb. If you have not read the content of the last two issues and do not know how to install the PHP extension to mongodb, please go back and read " PHP to mongodb" Extension (first acquaintance) " and "PHP extension to mongodb (newbie) ".
php connects 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 collection
$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));
Find data
Find a piece of data
$result= $collection->findone(array("name"=>"caleng"));
Query a list
// Find data whose creation time is greater than a certain time
$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); //Data start position
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"]}]
It can be seen that 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 are some simple operations written here. If you want to use php to work better with mongodb, then Read the manual.