DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> php對mongodb的擴展(小試牛刀)
php對mongodb的擴展(小試牛刀)
編輯:關於JavaScript     

今天外面刮著呼呼的大風,能在一個溫暖的小屋寫著博客也是北漂的一種幸福。好了廢話不多說,今天主要說一下php連接、操作mongodb,如果你沒有看上兩期的內容,不知道如何安裝php對mongodb的擴展的話請您返回去看《php對mongodb的擴展(初識如故) 》和《php對mongodb的擴展(初出茅廬)》 。

php 連接mongodb
復制代碼 代碼如下:
try {
  $mongo = new Mongo("mongodb://username:[email protected]:27017/db1");
}catch(MongoConnectionException $e) {
print $e->getMessage();
exit;
}

選擇數據庫blog
復制代碼 代碼如下:
$db = $mongo->blog;

關閉數據庫
復制代碼 代碼如下:
$conn->close();

選擇操作集合
$collection = $db->users;
插入數據
復制代碼 代碼如下:
$user = array('name' => 'caleng', 'city' => 'beijing');
$collection->insert($user);

修改數據
復制代碼 代碼如下:
$newdata = array('$set' => array("city" => "shanghai"));
$collection->update(array("name" => "caleng"), $newdata);

刪除數據
復制代碼 代碼如下:
$collection->remove(array('name'=>'caleng'), array("justOne" => true));

查找數據
查找一條數據
復制代碼 代碼如下:
$result= $collection->findone(array("name"=>"caleng"));

查詢一個列表
復制代碼 代碼如下:
//找出創建時間大於某一時間的數據
$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); //數據結束位置
$list_data->skip($start); //數據開始取的位置
var_dump($list_data);

in查詢
復制代碼 代碼如下:
$cursor = $collection->find(array(
'name' => array('$in' => array('Joe', 'Wendy'))
));

group查詢
復制代碼 代碼如下:
$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']);

輸出結果:
復制代碼 代碼如下:
[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

可以看出得到的結果是一個二維 數組
復制代碼 代碼如下:
array(
0 => array("category" =>"fruit", "items"=>array("apple","peach","banana")),
1 => array("category" =>"veggie", "items"=>array("corn","broccoli"))
)

在這裡這寫了一些簡單的操作,如果您想用php更好的作用mongodb 那就看手冊吧。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved