PHP程序中MongoDB数据库的基本操作
实例代码
// 连接$m = new Mongo();
// 连接数据库,不存在会自动创建
$db = $m->comedy;
// 选择集合,类似关系型数据库中选择表
$collection = $db->cartoons;
// 添加记录
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);
// 添加记录
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);
// 查询表中所有记录
$cursor = $collection->find();
// 输出
foreach ($cursor as $obj) {
echo $obj["title"] . "n";
}
?>
3、mongodb条件查询
使用find方法查找 “i” 为 71 的记录,
$query = array( "i" => 71 );$cursor = $collection->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
查找 i 大于 50的记录
$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
查找 20
$query = array( "i" => array( "$gt" => 20, "$lte" => 30 ) );
$cursor = $coll->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
4、创建索引
MongoDB 支持索引, 通过指定字段创建索引: 升序(1) or 降序 (-1). 以下代码是给 “i” 字段创建索引:
$coll->ensureIndex( array( "i" => 1 ) ); // create index on "i"$coll->ensureIndex( array( "i" => -1, "j" => 1 ) ); // index on "i" 降序, "j" 升序
?>
5、mongoDB更新数据
更新firstname 为Bob的address字段为1 Smith Lane”
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);
var_dump($c->findOne(array("firstname" => "Bob")));
?>
6、mongodb删除指定数据
$radioactive = $db->radioactive;// 统计type为94的所有数据量
$remaining = $radioactive->count(array('type' => 94));
$halflife = $remaining/2;
// 删除一般的数据justOne为true代表一个个删除
while ($halflife > 0) {
$radioactive->remove(array('type' => 94), array("justOne" => true));
$halflife--;
}
?>
通过id来删除mongoDB记录, 必须把id设置为 MongoID 对象 而不是字符串,例如以下
$id = '4b3f272c8ead0eb19d000000';// 无法删除:
$collection->remove(array('_id' => $id), true);
// 删除成功:
$collection->remove(array('_id' => new MongoId($id)), true);
?>
PHP程序中MongoDB数据库的基本操作