今天外面刮着呼呼的大风,能在一个温暖的小屋写着博客也是北漂的一种幸福。好了废话不多说,今天主要说一下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;
}
选择数据库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 那就看手册吧。