mongodb php library的使用

mongodb官方基于php7官方版本原生php7类库函数方法二次开发提供的php-library目前lib版本是1.6(即将1.7),安装过程也不复杂。但这里提供已经安装生成好的php-lib v1.6,可以拿去直接在php页面中调用。

注意:不论是否使用monogdb的二次封装的php-lib,你都需要下载php7的php mongodb扩展(mongodb的php驱动连接方法),下载地址如下,本文示例使用mongodb驱动版本1.7.5,为windows环境,如果是linux可在下方反馈,后期追加教程。然后在php.ini中引入,对于php7,你应该搜索mongodb,而非mongo(php5.x)

windows的安装可以使用wamp的方案。组件可以选择其中一部分 https://www.wampserver.com/en/

临时使用php内建的web (参考https://www.php.net/manual/en/features.commandline.webserver.php

在任意僧创建一个workspace目录,作为php测试的根目录,将php页面、或html页面放入。按如下以php.exe启动测试环境,在浏览器中访问http://127.0.0.5:9008/phpinfo.php,即可。如有报错将在根目录生成php_errors.log报错文件,以定位异常原因。


#  完整的php.exe 帮助
D:\server\php> .\php.exe -h
D:\server\php> .\php.exe  -c php.ini -S 127.0.0.5:9008 -t php_root/
PHP 7.2.32 Development Server started at Fri Jul 31 14:24:30 2020
Listening on http://127.0.0.5:9008
Document root is D:\server\php\php_root       
Press Ctrl-C to quit.
# 按Ctrl+c关闭服务

在linux中可以使用php-fpm来管理php进程。在windows中没有原生支持的,可以通过第三方工具实现服务化部署安装。官方文档在这里:https://www.php.net/manual/zh/install.windows.legacy.index.php

扩展php_mongodb.dll下载后放在php目录的ext文件夹中,然后在php.ini(此文件可简单通过复制同目录的文件php.ini-development的重命名来得到)中添加一行引入

extension=php_mongodb.dll

 创建一个phpinfo.php文件,文件内容如下:

<?php 
 phpinfo();
?>

phpinfo驱动加载成功的效果

mongodb官方的二次封装类库,需要php的扩展加载后才能正常使用哦。此类库的安装过程将在以后更新时补充,此处直接提供下载地址,解压即可使用,下文有require引入示例。

本示例中的mongodb为4.2版本(php7.4)。安装mongodb的教程可直接转到个人博客查看

对比:

  • php-lib语法更加接近mongo语法。但{ }要替换为[ ],:要替换为=>,这应该是php语言的特点。
  • php-lib对统计类aggregate() 函数的支持不足,或者可以说不能用,请留意。aggregate()还是需要使用php7的原生方法(下文有示例)

连接mongodb插入示例数据

mongo
> use yourmongodb
> db.yourcolletion.insert(
{
	"id": 11,
	"url_location": "/docs/evaluating/db_mysql01_performance_vs",
	"post_time_1": {
		"$date": "2020-02-24T15:03:31.667Z"
	},
	"post_title": "评估:mysql正式上线前的性能测试(基于sysbench202002)",
	"post_remark": null,
	"post_author": "author",
	"rating": "推荐",
	"catalogs": null,
	"tags": "mysql",
	"document_root": "somecode"
}
)

 


<?php
require '../../../cdn/vendor_mongodb_php_libs/vendor_1.6/autoload.php'; // include Composer's autoloader

// require 引入路径按实际相对于当前php页面的路径修改

$client = new MongoDB\Client("mongodb://localhost:27017");  //此处引用了PHP/LIB
$collection = $client->yourmongodb->youdbcollection;

//$result = $collection->find( [ 'rating' => '推荐'] );

$filter = ['id' => '11' ];  // 也可加条件限定  $filter = ['id' => [ '$gte' => 1 ]];
// 此处的$filter=[]条件变量时即为查询所有记录
$options = [
    'projection' =>['_id' => 0],
    'sort' => [ 'post_time_1' => -1 ],
	'limit' => 8,
];
//  但我们此处不用上面的$filter及$options直接将条件写入find()中
$result = $collection->find(  ['id' => [ '$gte' => 1 ]] ,['projection' =>['_id' => 0],'sort' => [ 'post_time_1' => -1 ],'limit' => 8,]);
//$result = $collection->find($filter, $options  );
// 此处为调用前面的$filter及$options


foreach ($result as $entry) {
    echo $entry['rating'], ': ',$entry['id'], ': ',$entry['post_time_1']->toDateTime()->format('m/d'), $entry['post_title'], $entry['rating'],"<hr>\n";
}

//db.poster.find({},{_id:0}).sort({post_time_1:-1}).pretty()
?>

下面是chrome测试效果页面

 

 

随机查询,样式页面还是上面的:

<?php
	$mongodb_client = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
	$command_random = new MongoDB\Driver\Command([
		'aggregate' => 'youcollection',
		'pipeline' => [
			['$sample' => ['size' => 8]],
			//指定随机选择8个文档记录
		],
		'cursor' => new stdClass,
	]);


	$cursor_random = $mongodb_client->executeCommand('yourmongodbdatabase', $command_random);
	// object转array (推荐)
	foreach ($cursor_random  as $document) {
	 
		$doc_array = (array)$document;
		$id =  $doc_array['id'];
		$post_title = $doc_array['post_title'];
		$rating = $doc_array['rating'];
		$post_time_1 = $doc_array['post_time_1'];
		$datetime = $post_time_1->toDateTime();  //转换为日期时间
		$day_month = $datetime->format('m/d'); // 月/日 12/12
		$url_location = $doc_array['url_location'];
		echo $entry['rating'], ': ',$entry['id'], ': ',$doc_array['post_time_1']->toDateTime()->format('m/d'), $doc_array['post_title'], $doc_array['rating'],"<hr>\n";
	}
?>

相关链接

https://docs.mongodb.com/php-library/v1.7/tutorial/

 

最后,本文将持续更新,请在正文留言反馈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值