Home >PHP Framework >ThinkPHP >Analyze the basic operations of mongo under the TP framework and its points of attention

Analyze the basic operations of mongo under the TP framework and its points of attention

藏色散人
藏色散人forward
2021-09-22 17:20:302481browse

The following thinkphp framework tutorial column will introduce you to the operation of mongo under thinkphp. I hope it will be helpful to friends in need!

Analyze the basic operations of mongo under the TP framework and its points of attention

1. Multiple conditional statements, many on the Internet are just one greater than or one Less than, there are no 2 merged ones, such as

$where['_string'] = 'this.b > 2 & this.b<4&#39;;

2.group

mysql:
$res = $model->where(['sTaskId'=>['$in'=>$task_array]])->group('a')->field('a,sum(a)')->select();

mongodb:
$key = ['a'=>1]; //groupby的字段
$init = ['num'=>0];//统计的初始值
$option = array(
'table' => 'course’, // 表名
'condition’=>['sTaskId'=>['$in'=>$task_array]], //group中过滤条件
);
//必须要带option
$reduce = "function(obj, prev){prev.num = prev.num+obj.a}";
$model = new TestModel();
$res = $model->group($key, $init, $reduce, $option);
这里讲一下tp的mongo扩展是有问题的,在group里调用where会无效,具体解决方案是要在mongo.class.php文件
a.把$query改为如下:
$query  =  $this->parseWhere(isset($options['condition'])?$options['condition']:array());
当然$this->queryStr  也要改的
b.把$group改为:
$group = $this->_collection->group($keys,$initial,$reduce,$query);

3 which is greater than 2 and less than 4. If you want to use the model model to query, and your main configuration is mysql , then you need to configure it in the configuration file first

'mongo' => [
DB_TYPE =>  mongo            
DB_HOST => localhost   
DB_NAME => test
DB_PORT =>  40000
DB_PREFIX =>'' 
DB_USER => ''
DB_PWD => ''
],

and then configure it in the model file,
a.protected $trueTableName = 'table name';
b.protected $connection = 'driver name, Here is mongo';
c. This model inherits MongoModel

4. Batch update

mysql里只要$res = $model->save(['a'=>1']);
mongo的话需要写成$res = $model->where([])->save(['a'=>1]);

5. Mongo note:

mongo对于数据类型的控制比较严格,如果你存个int的1,用'1'去查是查不到的!

Recommended: "The latest 10 thinkphp video tutorials"

The above is the detailed content of Analyze the basic operations of mongo under the TP framework and its points of attention. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete