php 連接mongodb
代碼如下:
try {
$mongo = new Mongo("mongodb://username:password@127.0.0.1:27017/db1");
}catch(MongoConnectionException $e) {
print $e->getMessage();
exit;
}
選擇數(shù)據(jù)庫blog
代碼如下:
$db = $mongo->blog;
關閉數(shù)據(jù)庫
代碼如下:
$conn->close();
選擇操作集合
$collection = $db->users;
插入數(shù)據(jù)
代碼如下:
$user = array('name' => 'caleng', 'city' => 'beijing');
$collection->insert($user);
修改數(shù)據(jù)
代碼如下:
$newdata = array('$set' => array("city" => "shanghai"));
$collection->update(array("name" => "caleng"), $newdata);
刪除數(shù)據(jù)
代碼如下:
$collection->remove(array('name'=>'caleng'), array("justOne" => true));
查找數(shù)據(jù)
查找一條數(shù)據(jù)
代碼如下:
$result= $collection->findone(array("name"=>"caleng"));
查詢一個列表
代碼如下:
//找出創(chuàng)建時間大于某一時間的數(shù)據(jù)
$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); //數(shù)據(jù)結束位置
$list_data->skip($start); //數(shù)據(jù)開始取的位置
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"]}]
可以看出得到的結果是一個二維 數(shù)組
代碼如下:
array(
0 => array("category" =>"fruit", "items"=>array("apple","peach","banana")),
1 => array("category" =>"veggie", "items"=>array("corn","broccoli"))
)
在這里這寫了一些簡單的操作,如果您想用php更好的作用mongodb 那就看手冊吧。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com