MongonDb在thinkphp中常用的功能整理(模糊查询)
1.以某字段开头的数据查询条件
$title = input('param.title');
$where['title'] = new \MongoDB\BSON\Regex("^{$title}",'i'); //已title开头的字
//tp3.2.3亲测
if (!empty($params['Domain'])) {
$where['domain_name'] = ['regex', '/.*'.$params['Domain'].'.*/'];
}
$pipeline = [
[
'$match' =>
[
'domain_status' => ['$ne' => 0],
'user_id' => ['$in' => $where['user_id'][1]]
]
],
['$sort' => ['domain_id' => -1]]
];
$result = (new DomainInfoService())->getAggregateList($pipeline);
public function getAggregateList($pipeline, $options = []){
return D($this->model)->aggregate($pipeline,$options);
}
2.原生用法:
//query 查询列表
$command = new \MongoDB\Driver\Query($where);
$manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$lists = $manager->executeQuery("news.friend_circle", $command);
var_dump($lists->toArray());
//command用法
$command = new \MongoDB\Driver\Command($document);
var_dump($command);
$list = $mongoModel->Command($command,"friend_circle");
var_dump($list);
3.根据某字段模糊查询
1)命令行:db.news_live.find({"title":/测试?/i});
2)代码查询
$query
=
array
(
"name"
=>
new
MongoRegex(
"/.*”.$name."
.*/i"));
3.根据数据库某字段排序(比如根据时间排序)
$order = array('create_time'=>-1); //-1表示降序,1表示升序
$list = $mongo->order($order)->select();
public function selectUidRoomMsgGroupByMsgDate($startTime, $endTime, $length = 100) {
$result = D($this->model)->aggregate([
['$match' => ['date' => ['$gte' => $startTime, '$lte' => $endTime]]],
[
'$project' => [
'_id' => 0,
'message_id' => '$message_id',
'cuid' => '$cuid',
'date' => '$date',
'owner_user_id' => '$owner_user_id',
'room_name' => '$room_name',
]
],
[
'$group' => [
'_id' => ['msg' => '$message_id', 'date' => '$date'],
'count' => ['$sum' => 1],
"document" => ['$first' => '$$ROOT']
]
],
['$limit' => $length]
]);
return empty($result) ? [] : $result;
}