一、软件环境(版本非必须) php v5.6 扩展:MongoDB nginx v1.11 mongodb v3.2
note: 必须安装MongoDB扩展
二、连接 $client = new MongoClient($server, $option);
$server 变量是个字符串,描述要连接的服务器
mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
其中必要的是:
username 数据库用户名 password 数据库密码 host 服务器地址 port 数据库监听端口 三、选表(集合) 选择数据库 选择集合 $db = $client->{$db_name};
返回MongoDB类 类文档传送门
$collection = $db->{$collection_name};
返回MongoCollection类 类文档传送门
四、查询数据 $cursor = $collection->find($filter);
返回MongoCursor类 类文档传送门
1. $filter参数
mongoshell find函数参数使用:传送门
php代码编写
// 查询值大于value的文档 $filter[$gtKey] = array('$gt' => $value); // regexKey模糊查询 $filter[$regexKey] = new MongoRegex('/'.$regexValue.'/'); $collection->find($filter);
注意:
模糊查询需要使用MongoRegex类来使用,否则不识别 比较大小时,$value 的值需要与mongodb中存储的类型一致 2. 利用MongoCursor进行分页等操作 // 返回MongoCursor,可以利用MongoCursor的方法遍历数据 // 或者使用iterator_to_array($cursor)转换成数组 $cursor = $cursor ->sort(array($field=>'-1 or 1')) // 1是正序,-1是反序 ->skip($start) // 数据起始位置 ->limit($size); // 数据结束位置为$start+$size // 返回int型数值 $count = $cursor ->find($filter) ->count(); $data = iterator_to_array($cursor)
不再讲解如何使用MongoCursor遍历数据
五、总结
使用php连接MongoDB查询数据总体来说非常简单。连接、根据条件查询、分页,三步搞定。
注意事项:
使用单例模式获取MongoDB实例 模糊查询需要借助MongoRegex类 操作完成要** 关闭连接 **
That’s right. This article was first published in March 2016, buttimes change, new themes are launched for sale, so we’ve stripped out themes which are no longer available andadded eight new examples to keep things up to date.
1. Introduce Yourself
Emotional design is hugely important on the web; add the “human element” to your portfolio and your visitors will more likely connect with the work you show them. Make sure they know who they’re dealing with, who’s responsible for the photos, and who it is they’ll need to get in touch with if they want to know more.
The Responsive Photography Theme by ThemeGoods offers a homepage layout which does this really well. Your name, your signature, a touch of personality up front and centre.