php对mongodb的扩展(小试牛刀)
今天外面刮着呼呼的大风,能在一个温暖的小屋写着博客也是北漂的一种幸福。好了废话不多说,今天主要说一下php连接、操作mongodb,如果你没有看上两期的内容,不知道如何安装php对mongodb的扩展的话请您返回去看《php对mongodb的扩展(初识如故) 》和《php对mongodb的扩展(初出茅庐)》 。
try {
$mongo = new Mongo("mongodb://username:password@127.0.0.1:27017/db1");
}catch(MongoConnectionException $e) {
print $e->getMessage();
exit;
}
$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);
$cursor = $collection->find(array(
'name' => array('$in' => array('Joe', 'Wendy'))
));
$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 那就看手册吧。