thinkphp 怎么用mongodb作为辅助数据库
连接数据库
$conn=new Mongo(“mongodb://sa:123@localhost”); #带用户名密码
选择数据库和集合
$db=$conn->selectDB(“mydb”);
$collection = $db->selectCollection(‘column’);
增删改查
1.插入
$array=array(‘column_name’=>’col’.rand(100,999),’column_exp’=>’xiaocai’);
$result=$collection->insert($array); #简单插入
2. 修改更新
$where=array(‘column_name’=>’col123′);
$newdata=array(‘column_exp’=>’GGGGGGG’,'column_fid’=>444);
$result=$collection->update($where,array(‘$set’=>$newdata));
3.删除
$where=array(‘column_name’=>’col685′);
$result=$collection->update($where,array(‘$unset’=>’column_exp’));
4.查询
$result = $collection->find();
2017-04-10
//.配置MySQL数据库
'DB_MYSQL' => array(
'db_type'=>'mysqli',
'db_user'=>'用户名',
'db_pwd'=>'密码',
'db_host'=>'127.0.0.1',
'db_port'=>'3306',
'db_name'=>'数据库名',
'db_charset'=>'utf8',
),
//.配置MongoDB数据库
'DB_MONGO' => array(
'db_type'=>'mongo',
'db_user'=>'用户名',
'db_pwd'=>'密码',
'db_host'=>'localhost',
'db_port'=>'27017',
'db_name'=>'数据库名',
),
复制代码
2. 写一个M函数,实现数据库的调用
//. 调用MONGO和MYSQL数据库
protected function M( $table_name = '', $db_type = 'DB_MYSQL' ){
$db_config = C($db_type);
$db_prefix = C('DB_PREFIX');
if( $table_name == '' ){ return false; }
if( $db_type == 'DB_MYSQL' ){
return M( $table_name , $db_prefix , $db_config );
}else if( $db_type == 'DB_MONGO' ){
return M( '\Think\Model\MongoModel:' . $table_name , $db_prefix , $db_config );
}else{
return false;
}
}//;
复制代码
3. 调用M函数的实例
//. 调用自定义的M函数
//. 连接MySQL数据库
echo 'Mysql:';
$list = $this->M('user','DB_MYSQL')->select();
dump( $list );
//. 连接MongoDB数据库
echo 'Mongo:';
$list = $this->M('user','DB_MONGO')->select();
dump( $list );