您的位置:首页 > 数据库 > Mongodb

tp5+Mongodb与Mysql数据库的混合查询

2018-01-07 16:52 405 查看

前言

MongoDB 海量数据查询快速 不需要建立数据模型
适合做日志数据库
或者中间数据库 从MySQL数据库中读取存放一些需要读的业务数据
MongoDB没有适合多表事务功能,写操作也没有多好的确定机制,不适合当做业务数据的数据库

MySQl 存放业务数据 事务的读写


实现过程

配置database

<?php

return [
// 数据库类型
'type'            => '\think\mongo\Connection',
// 服务器地址
'hostname'        => 'localhost',
// 数据库名
'database'        => 'tuzi',
// 用户名
'username'        => '',
// 密码
'password'        => '',
// 端口
'hostport'        => '27017',
// 连接dsn
'dsn'             => '',
// 数据库连接参数
'params'          => [],
// 数据库编码默认采用utf8
'charset'         => 'utf8',
// 数据库表前缀
'prefix'          => '',
];


配置config

'mysql_db'  => [
// 数据库类型
'type'            => 'mysql',
// 服务器地址
'hostname'        => 'localhost',
// 数据库名
'database'        => 'tuzi',
// 用户名
'username'        => 'root',
// 密码
'password'        => '111',
// 端口
'hostport'        => '',
// 连接dsn
'dsn'             => '',
// 数据库连接参数
'params'          => [],
// 数据库编码默认采用utf8
'charset'         => 'utf8',
// 数据库表前缀
'prefix'          => '',
// 数据库调试模式
'debug'           => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy'          => 0,
// 数据库读写是否分离 主从式有效
'rw_separate'     => false,
// 读写分离后 主服务器数量
'master_num'      => 1,
// 指定从服务器序号
'slave_no'        => '',
// 是否严格检查字段是否存在
'fields_strict'   => true,
// 数据集返回类型
'resultset_type'  => 'array',
// 自动写入时间戳字段
'auto_timestamp'  => false,
// 时间字段取出后的默认时间格式
'datetime_format' => 'Y-m-d H:i:s',
// 是否需要进行SQL性能分析
'sql_explain'     => false,
]


代码实现

<?php
namespace app\index\controller;
use think\Db;
class Index
{
public function index()
{
echo "--------我是通过mongodb查询出来的数据----------<br/>";
$data = array('a'=>'元素1','b'=>'元素2');
// Db::table('document')->insert($data);
$res = Db::table('document')->select();
dump($res);
echo "--------我是通过mysql查询出来的数据----------<br/>";
$res1 = Db::connect(Config('mysql_db'))->table('admin')->select();
dump($res1);
return "成功完成";
}
}


运行结果

--------我是通过mongodb查询出来的数据----------
array(3) {
[0] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)#12 (1) {
["oid"] => string(24) "5a51bf6583869e4b62321af3"
}
["a"] => string(7) "元素1"
["b"] => string(7) "元素2"
}
[1] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)#13 (1) {
["oid"] => string(24) "5a51bfa083869e4b647a61c6"
}
["a"] => string(7) "元素1"
["b"] => string(7) "元素2"
}
[2] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)#14 (1) {
["oid"] => string(24) "5a51c30383869e4b674156f6"
}
["a"] => string(7) "元素1"
["b"] => string(7) "元素2"
}
}
--------我是通过mysql查询出来的数据----------
array(1) {
[0] => array(3) {
["admin_id"] => int(1)
["user_name"] => string(5) "admin"
["password"] => string(3) "888"
}
}
成功完成 0.030056s ShowPageTrace
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: