• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP从MongoDb中查询数据怎么样实现

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、软件环境(版本非必须) 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.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php为什么要用swoole?发布时间:2022-07-10
下一篇:
PHP设计模式-观察者模式发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap