Heim  >  Artikel  >  Backend-Entwicklung  >  MongoDB在PHP中的常用操作小结_PHP

MongoDB在PHP中的常用操作小结_PHP

WBOY
WBOYOriginal
2016-06-01 11:56:02772Durchsuche

MongoDB

$mongodb = new Mongo();

//$connection = new Mongo( "$dburl:$port" ); // connect to a remote host (default port)

$mydb = $mongodb->mydb;  //隐性创建数据库mydb

$mydb = $mongodb->selectDB("mydb");  //直接选择已经存在的数据库

$collection = $mydb->mycollect;   //选择所用文集,如果不存在,自动创建

$collection = $db->selectCollection('mydb');   //只选择,不创建

//插入新纪录

$collection->insert(array("name"=>"l4yn3", "age"=>"10", "sex":"unknow"));


//修改记录

$where = array("name"=>"l4yn3");

$update_item = array('$set'=>array("age"=>"15", "sex":"secret"));

$collection->update($where, $update_item);

$options['multiple'] = true; //默认是 false,是否改变匹配的多行

$collection->update($where, $update_item, $options);


//查询记录

$myinfo = $collection->findOne(array("name"=>"l4yn3"));

$myinfo = $collection->findOne(array("name"=>
"l4yn3"), array("age"=>"15"));


//按条件查找:
$query = array("name"=>"l4yn3");
$cursor = $collection->find($query); //在$collectio集合中查找满足$query的文档
while($cursor->hasNext())
{
var_dump($cursor->getNext()); //返回了数组
}


//返回文档记录数量

$collection->count();


//删除一个数据库:
$connection->dropDB("...");

//列出所有可用数据库:
$m->listDBs(); //无返回值
//关闭连接:
$connection->close();

php各种连接mongodb数据库的参数方式

//连接localhost:27017
$conn = new Mongo();
//连接远程主机默认端口
$conn = new Mongo('test.com');
//连接远程主机22011端口
$conn = new Mongo('test.com:22011');
//MongoDB有用户名密码
$conn = new Mongo("mongodb://${username}:${password}@localhost")
//MongoDB有用户名密码并指定数据库blog
$conn = new Mongo("mongodb://${username}:${password}@localhost/blog");
//多个服务器
$conn = new Mongo("mongodb://localhost:27017,localhost:27018");

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn