Skip to main content

Mongodb 快速上手

MongoDb

官网
安装环境Centos 6.7 x64

安装

Binary安装

curl -o mongo.tar.gz https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.4.2.tgz  
tar -xvzf mongodb-linux-x86_64-rhel62-3.4.2.tgz  
cd mongodb-linux-x86_64-rhel62-3.4.2  
bin中的就是mongodb的程序,记得将路径加入环境变量  
export PATH=<mongodb-install-directory>/bin:$PATH  

Yum安装

创建repo文件在/etc/yum.repos.d/mongodb-org-3.4.repo,内容如下:

[mongodb-org-3.4]
name=MongoDB Repository  
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/  
gpgcheck=1  
enabled=1  
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc  

最新内容参考这里Yum Install

yum makecache  
yum list all | grep mongo  
yum install mongodb-org -y  

配置

关闭SELINUX

setenforce 0  

创建数据目录和配置文件
配置文件如下:

#auth                            = 1
#bind_ip                         = 192.168.223.144
cpu                             = 1  
dbpath                          =  /mongo/node-27017  
#diaglog                         = 3
directoryperdb                  = 1  
fork                            = 1  
journal                         = 1  
logappend                       = 1  
logpath                         = /mongo/node-27017/mongod.log  
maxConns                        = 3000  
oplogSize                       = 10240  
pidfilepath                     = /mongo/node-27017/mongod.pid  
port                            = 27017  
profile                         = 1  
#repair                          = 0
repairpath                      = /mongo/node-27017  
#rest                            = 0
slowms                          = 100  
smallfiles                      = 1  
#verbose                         = 1
noscripting                     = 1  
#keyFile                         = /mongo/mongo_key
#autoresync                      = 1
#fastsync                        = 1
shardsvr=true



#source = 10.21.76.156:27017
#slavedelay = 0
#autoresync = false
noobjcheck=true  
#日志
#syslog = false
journalCommitInterval = 100  
nohttpinterface = true  
notablescan = false  
syncdelay = 60  
#pid文件
#是否启动守护模式
#数据库文件
#noprealloc=false
storageEngine=wiredTiger    #3.0新有的引擎  
#wiredTigerCacheSizeGB=12
#wiredTigerStatisticsLogDelaySecs=0
#wiredTigerJournalCompressor=snappy
#wiredTigerDirectoryForIndexes=true
#wiredTigerCollectionBlockCompressor=snappy
#wiredTigerIndexPrefixCompression=1

单实例

启动

mongod -f /data/mongodb_data/cnf/mongo-27107.cnf  

对mongodb禁用num模式启动

numactl --interleave=all /usr/bin/mongod -f /data/mongodb_data/cnf/mongo-27107.cnf  

停止

发送Kill来安全停止

kill -2 pid  
或者
kill -4 pid  

通过命令行安全停止
连接Mongodb

mongo localhost:27017  

关闭mongodb

use admin;  
db.shutdownServer();  

命令行连接

mongo 192.168.0.249:27017  

客户端中的CRUD

参考资料

检查当前所在数据库

db  

使用数据库, 如果数据库不存在将会创建他

use databasename  

列出所有可用数据库

show dbs  

删除Collection中的所有数据

db.testCollection.remove({});  

给Collection创建索引

db.testCollection.ensureIndex({'username':1});  

给Collection创建唯一索引

db.testCollection.ensureIndex({"username":1},{"unique":true});  

列出已经创建的索引

db.post_log.getIndexes();  

删除索引

db.pets.dropIndex( { "cat" : -1 } )  

Mongodb 设置密码

官方参考

在配置文件中修改配置

# 开启验证
auth = 1  

然后重启数据库。

添加超级管理用户

use admin;  
db.createUser({user:"root",pwd:"zip107",roles:["root"]});  
登陆这个用户
use admin;  
db.auth("root","zip107");  

添加数据库用户

注意添加数据库用户前,需要使用超级管理员登陆一次验证。

切换到数据库
use rtb;  
将数据库分配给用户
db.createUser({user:"rtb",pwd:"xiaocan",roles:[{role:"dbOwner",db:"rtb"}]});  

查看用户

db.system.users.find();  

删除用户


PHP基本使用

编译安装扩展

官方参考
Mac依赖:

brew install openssl

git clone https://github.com/mongodb/mongo-php-driver.git  
cd mongo-php-driver/  
git submodule sync && git submodule update --init  
phpize  
# Centos 
./configure --with-php-config=php-config
# Mac
./configure --with-php-config=php-config --with-openssl-dir=/usr/local/opt/openssl
make all -j 5  
make test  
make install  

Centos 安装方法2:

pecl install mongodb

然后在PHP中打开扩展

安装Mongo库支持

php composer.phar require mongodb/mongodb  

基本使用

print_r("<pre>");  
# Connect to mongodb
$manager = new MongoDB\Client("mongodb://192.168.0.249:27017");
# Connect to mongodb by user and database
$manager = new MongoDB\Client("mongodb://rtb:xiaocan@192.168.0.249:27017/rtb");
# Choose database
$db = $manager->xc;
# Select collection
$table = $db->testCollection;

# Insert Single Data
$ret = $table->insertOne(array(
    'email'=>time(),
    'username'=>'fgy58963',
    'password'=>'xiaocan',
    'nickname'=>'xiaocan'
    ));
# Get Result And Insert Id
print_r("Insert Id: ".$ret->getInsertedId());

# Insert Multiple Data
$ret = $table->insertMany(array(
    array(
        'email'=>time()+3,
        'username'=>'fgy58963',
        'password'=>'xiaocan',
        'nickname'=>'xiaocan'
        ),
    array(
        'email'=>time()+1,
        'username'=>'fgy58963',
        'password'=>'xiaocan',
        'nickname'=>'xiaocan'
        ),
    array(
        'email'=>time()+2,
        'username'=>'kpi_test',
        'password'=>'xiaocan',
        'nickname'=>'xiaocan'
        )
    ));

print_r("Insert Data Count: ".$ret->getInsertedCount());  
print_r($ret->getInsertedIds());

# Find Single Log  
$rec = $table->findOne(array('email'=>time()+2,'username'=>'kpi_test'));
var_dump($rec);  
$rec = $table->findOne(array('email'=>time(),'username'=>'kpi_test'));
var_dump($rec);

# Find Multiple Log
$mrec = $table->find(array());
# Find with sort and limit and skip rows
//http://php.net/mongodb-bson-regex
$mrec = $table->find(
    array("username"=>new MongoDB\BSON\Regex('^fgy','i'))
    ,array(
        "sort"=>array("email"=>-1) # -1 or 1 for incr or desc
        ,"limit"=>5
        ,"skip"=>5
    ) 
    );
foreach ($mrec as $value) {  
    echo "Email: ".$value->email." Username: ".$value->username."<br />";
}
echo "Count Data:<br />";  
# Count data
# https://docs.mongodb.com/manual/core/aggregation-pipeline/
$mrec = $table->aggregate(
    array(
        array('$group'=>array('_id'=>'$username','count'=>array('$sum'=>1))),   # 如果要计算数量,就将sum=1
        array('$sort'=>array('count'=>-1)),
        array('$limit'=>1) # 在处理的结果上limit
        )
    );
foreach ($mrec as $value) {  
    echo "Username: ".$value->_id." Email_Count: ".$value->count."<br />";
}

echo "Sum Data:<br />";  
# Sum data
$mrec = $table->aggregate(
    array(
        array('$match'=>array('$or'=>array(
            array('email'=>array('$lt'=>1489144422)), # lt -> Less than
            array('email'=>array('$gte'=>1489543398,'$lte'=>1489543465)) # gte -> greater than and equal
        ))), # or匹配和 数值范围匹配
        array('$group'=>array('_id'=>'$username','count'=>array('$sum'=>'$email'))), # 如果要统计数字求和,就指定求和的字段
        array('$sort'=>array('count'=>-1)),
        array('$limit'=>2),
        array('$skip'=>0)
        )
    );
foreach ($mrec as $value) {  
    echo "Username: ".$value->_id." Email_Count: ".$value->count."<br />";
}

Yaf + ODM

这里推荐使用jenssegers/laravel-mongodb,其封装和使用基本与原Eloquent Orm相同
Github

Install

composer require jenssegers/mongodb  

Edit File

因为jenssegers/mongodb是以使用Laravel框架为基础来进行开发的,所以在切换到Yaf框架的时候会抛出 Call to member function的异常,最简单快捷的解决方法:
修改Mongodb/Query/Builder.php,找到函数shouldUseCollections
修改前:

protected function shouldUseCollections()  
{
    if (function_exists('app')) {
        $version = app()->version();
        $version = filter_var(explode(')', $version)[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // lumen
        return version_compare($version, '5.3', '>=');
    }
}

修改后:

protected function shouldUseCollections()  
{
    return true;
}

Yaf->application.ini

数据库配置文件如下:

;database
database.mysql.driver     = mysql  
database.mysql.host = '192.168.0.249'  
database.mysql.database   = tf  
database.mysql.username   = root  
database.mysql.password   = "xiaocan"  
database.mysql.port       = 3306  
database.mysql.charset    = 'utf8'  
database.mysql.collation  = 'utf8_general_ci'  
database.mysql.prefix     = ''

database.mongodb.host = "192.168.0.249,";  
database.mongodb.driver = mongodb;  
database.mongodb.port = '27017';  
database.mongodb.username = 'rtb';  
database.mongodb.password = 'xiaocan';  
database.mongodb.database = 'rtb';  
database.mongodb.options.database = 'rtb';

database.default = 'mongodb';  

Yaf->Bootstrap.php

public function _initDb(\Yaf\Dispatcher $dispatcher)  
{
    $config = \Yaf\Application::app()->getConfig()->database->toArray();
    $capsule = new Capsule();

    // Get Default database settings
    if($config['default'] == 'mysql'){
        $capsule->getDatabaseManager()->setDefaultConnection('mysql');
    }
    if($config['default'] == 'mongodb'){
    // Set default connection
    $capsule->getDatabaseManager()->setDefaultConnection('mongodb');
    }
    // 创建链接
    $capsule->addConnection($config['mysql'],'mysql');
    // 设置处理模式
    $capsule->getDatabaseManager()->extend('mongodb', function($config){
        $j =  new MongoConnection($config);
        return $j;
    });
    // Set Mongodb host
    $host = explode(',', $config['mongodb']['host']);
    $config['mongodb']['host'] = array_filter($host,function($v){return $v !== '';});
    // 创建链接
    $capsule->addConnection($config['mongodb'],'mongodb');
    // 设置全局静态可访问
    $capsule->setAsGlobal();
    // 启动Eloquent
    $capsule->bootEloquent();
}

ODM Using

Create Base Class

在application/models创建文件夹MongoOrm,并创建父类Moloquent.php:

<?php  
    namespace MongoOrm;
    use Jenssegers\Mongodb\Eloquent\Model;
    class MoloquentModel extends Model
    {
        // todo
        //protected static $redis = XcRedis\XcRedis::getInstance();

        public function __construct(){
        }

    }
?>

Create Odm Class

如果要Mysql和Mongodb在Eloquent下共存,Class中必须包含connection属性
创建文件PostLog.php

<?php  
    namespace MongoOrm;
    use Illuminate\Database\Capsule\Manager as DB;
    use Jenssegers\Mongodb\Eloquent\HybridRelations;
    class PostLogModel extends MoloquentModel
    {
        //必须 表名
        public $collection = 'post_log';

        public $connection = 'mongodb';

        public $primaryKey = "_id";

        //非必须,如果使用软删除就是必须,需要数据库表中存在字段:created_at updated_at deleted_at
        public $timestamps = false;

    }
?>

Use

总体来说使用方法和ORM相同,区别的地方参照github可以得到解释:

public function indexGETAction(){  
    $data = MongoOrm\PostLogModel::where('time','<',0)->get();
    var_dump(count($data));

    //var_dump(DB::collection('win_log')->get());
    return false;
}

分片

副本集群