数据库

 首页 > 数据库 > MongoDB > PHP程序中MongoDB数据库的基本操作

PHP程序中MongoDB数据库的基本操作

分享到:
【字体:
导读:
         摘要:实例代码?php//连接$mnewMongo();//连接数据库,不存在会自动创建$db$m-comedy;//选择集合,类似关系型数据库中选择表$collection$db-cartoons;//添加记录$objarray(titleCalvinandHobbes,authorBillWatterson);$coll...

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”

$c->insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$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数据库的基本操作
分享到:
在ASP.NET程序中使用MongoDB数据库
在ASP.NET程序中使用MongoDB数据库 首先:驱动 如果asp.net 想使用MongoDB,.net没有自带的链接类。得用第三方或官方的链接类。 当然有很多种驱动,我就不一一介绍了。 今天我就介绍一个我比较常用的驱动-----MongoDB。 接下来,我们还要去下载MongoDB的C#驱动,它可以让我们在C#中使用MongoDB 。下载地址...
MongoDB数据库安装使用记录
MongoDB数据库安装使用记录 感觉要继续菜去了...可是,地球已经调至震动状态,我得坚持看些东西,不然就来不及了...时间就像牙膏,只要挤,总会有的! 简介 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。   MongoDB是一个介于关系数...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……