Home > php教程 > php手册 > MongoDB在PHP中的常用操作小结

MongoDB在PHP中的常用操作小结

WBOY
Release: 2016-06-06 20:24:42
Original
1280 people have browsed it

本篇文章主要是对MongoDB在PHP中的常用操作进行了详细的总结介绍,需要的朋友可以过来参考下,希望对大家有所帮助

$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");

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template