本文主要记录一次用php7 MongoDB\Driver操作mongo的复杂查询。基本查询网上有很多,本文就不在赘述了。推荐去php官网查看相关文档。
本次查询相关代码
define('MONGO_DSN', 'mongodb://127.0.0.1:27018/?readPreference=primaryPreferred');
$mongo = new MongoDB\Driver\Manager(MONGO_DSN);
$filter = array(
'is_delete'=>false,
'app'=>array('$exists'=>true),
'$or'=>array(
array('app.enable'=>array('$ne'=>'on')),
array(
'app.enable'=>'on',
'app.url.0'=>array('$exists'=>true)
)
)
);
$options = array(
'projection'=>array('_id'=>0, 'domain'=>1, 'port'=>1, 'app'=>1)
);
$table = "mydb.test";
$query = new MongoDB\Driver\Query($filter,$options);
$preference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED);
$cursor = $mongo->executeQuery($table,$query,$preference);
$rows = json_decode(json_encode($cursor->toArray()),true);
代码解析
数据库地址基本格式: mongodb://用户名:密码@ip:端口/。本文因为是mongo主从readPreference为查询从库优先($preference同)。还有很多其它设置,可以根据自己的需求选择。
查询设置:根据本文查询条件($filter)和显示设置($options)转为sql语句如下:
SELECT domain, port, app from mydb.test where is_delete=false and app is not null and (app.enable != ‘on’ or app.url.0 is not null )。
app.url.0’=>array(’$exists’=>true) 这样写不知道对不对, mongo中含义为app.url数组中最少有一个元素
表名:mydb.test (库名:mydb,表名:test)
格式转换: json_decode(json_encode($cursor->toArray()),true); 最后转为json格式。