zoukankan      html  css  js  c++  java
  • 37_MongoDB副本集 MongoDB文档管理

    版本:3.6.3

    一、部署MongoDB副本集
    1.1 启用副本集配置并指定集群名称 rs1
    1.2 定义集群成员列表
    部署好机器51,52,53:51上配置
    ]# vim /usr/local/mongodb/etc/mongodb.conf
    bind_ip=192.168.4.51(要改)
    port=27051(要改)
    logpath=/usr/local/mongodb/log/mongodb.log
    logappend=true
    dbpath=/usr/local/mongodb/data/db
    fork=true
    replSet=rs1(51 52 53都一样)

    (51 52 53都一样)
    启动
    ]# /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/etc/mongodb.conf
    ]# alias startmdb='/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/etc/mongodb.conf'
    ]# alias stopmdb='/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/etc/mongodb.conf  --shutdown'
    查看服务信息
    ]# ps -C mongod
    PID TTY          TIME CMD
    18252 ?        00:00:00 mongod
    都有东西:
    ]# ls /usr/local/mongodb/log/
    mongodb.log

    51操作
    ]#/usr/local/mongodb/bin/mongo --host 192.168.4.51 --port 27051 (回车)
    > config={
    _id:"rs1",
    members:[
    {_id:0,host:"192.168.4.51:27051"},
    {_id:1,host:"192.168.4.52:27052"},
    {_id:2,host:"192.168.4.53:27053"}
    ]}
     
    {
    "_id" : "rs1",
    "members" : [
    {
    "_id" : 0,
    "host" : "192.168.4.51:27051"
    },
    {
    "_id" : 1,
    "host" : "192.168.4.52:27052"
    },
    {
    "_id" : 2,
    "host" : "192.168.4.53:27053"
    }
    ]
    }

    1.3 创建集群
    > rs.help()
    > rs.help()
    rs.status()                                { replSetGetStatus : 1 } checks repl set status
    rs.initiate()                              { replSetInitiate : null } initiates set with default settings
    rs.initiate(cfg)                           { replSetInitiate : cfg } initiates set with configuration cfg
    rs.conf()                                  get the current configuration object from local.system.replset
    rs.reconfig(cfg)                           updates the configuration of a running replica set with cfg (disconnects)
    rs.add(hostportstr)                        add a new member to the set with default attributes (disconnects)
    rs.add(membercfgobj)                       add a new member to the set with extra attributes (disconnects)
    rs.addArb(hostportstr)                     add a new member which is arbiterOnly:true (disconnects)
    rs.stepDown([stepdownSecs, catchUpSecs])   step down as primary (disconnects)
    rs.syncFrom(hostportstr)                   make a secondary sync from the given member
    rs.freeze(secs)                            make a node ineligible to become primary for the time specified    rs.remove(hostportstr)                     remove a host from the replica set (disconnects)    rs.slaveOk()                               allow queries on secondary nodes

    rs.printReplicationInfo()                  check oplog size and time range
    rs.printSlaveReplicationInfo()             check replica set members and replication lag
    db.isMaster()                              check who is primary

    > rs.initiate(config)
    {
        "ok" : 1,
        "operationTime" : Timestamp(1580874045, 1),
        "$clusterTime" : {
            "clusterTime" : Timestamp(1580874045, 1),
            "signature" : {
                "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                "keyId" : NumberLong(0)
            }
        }
    }

    rs1:SECONDARY>
    rs1:PRIMARY>
     
    1.4 查看集群信息
    > rs.status()
    > rs.isMaster()
    {
        "hosts" : [
            "192.168.4.51:27051",
            "192.168.4.52:27052",
            "192.168.4.53:27053"
        ],
        "setName" : "rs1",
        "setVersion" : 1,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "192.168.4.51:27051",
        "me" : "192.168.4.51:27051",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
            "opTime" : {
                "ts" : Timestamp(1580874178, 1),
                "t" : NumberLong(1)
            },
            "lastWriteDate" : ISODate("2020-02-05T03:42:58Z"),
            "majorityOpTime" : {
                "ts" : Timestamp(1580874178, 1),
                "t" : NumberLong(1)
            },
            "majorityWriteDate" : ISODate("2020-02-05T03:42:58Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2020-02-05T03:43:02.751Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "minWireVersion" : 0,
        "maxWireVersion" : 6,
        "readOnly" : false,
        "ok" : 1,
        "operationTime" : Timestamp(1580874178, 1),
        "$clusterTime" : {
            "clusterTime" : Timestamp(1580874178, 1),
            "signature" : {
                "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                "keyId" : NumberLong(0)
            }
        }
    }
     
    1.5 客户端50 访问集群存取数据
    ]#/usr/local/mongodb/bin/mongo --host 192.168.4.51 --port 27051
    >show dbs
    admin   0.000GB
    config  0.000GB
    local   0.000GB

    在从库自己连接自己 查看是否有主库的数据(52为例)
    允许对数据做操作  >db.getMongo( ).setSlaveOk( ) //从库要
    ]# /usr/local/mongodb/bin/mongo --host 192.168.4.52 --port 27052
    rs1:SECONDARY> db.getMongo( ).setSlaveOk( )
    rs1:SECONDARY> show dbs;
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    rs1:SECONDARY> use db15
    switched to db db15

    rs1:SECONDARY> db.a.save({name:"bob",age:19})
    rs1:SECONDARY> db.a.find()
    { "_id" : ObjectId("5e3a3ae8b82d985ba1e65416"), "name" : "bob", "age" : 19 }
     
    1.6 测试集群功能(高可用功能测试)
    停止当前主库的mongodb服务,
    在2个副本主机查看集群状态信息(两个副本机会随机选举一个作为主库)
    把坏掉的主库修复后会自动配置位当前主库的副本主机并自动同步宕机期间的数据
     
    二、文档管理 192.168.4.50
    把/etc/passwd 文件的内容存储到bbsdb库下的user6集合里
    (使用备份文件恢复 或 数据导入 都可以 完成)

    2.1 增
    ]# /usr/local/mongodb/bin/mongo --host 192.168.4.50 --port 27050
    插入文档 save()  insert()  insertMany()
    > db.a.save({_id:1,name:"bob"})
    > db.a.save({_id:2,name:"jerry"})
    > db.a.find()
    { "_id" : 1, "name" : "bob" }
    { "_id" : 2, "name" : "jerry" }

    > db.a.insert({_id:1,name:"lucy"})
    > db.a.insert({_id:2,name:"lucy"})
    ID重复,插入数据错误!
    "errmsg" : "E11000 duplicate key error collection: bbsdb.a index: _id_ dup key: { : 2.0 }"

    > db.a.insert({_id:3,name:"lucy"})
    > db.a.find()  //插入成功
    { "_id" : 1, "name" : "bob" }
    { "_id" : 2, "name" : "jerry" }
    { "_id" : 3, "name" : "lucy" }

    > db.a.insertMany([ {_id:4,name:"lucyA"} , {name:"liliBB"} ,{age:1} ])
    > db.a.find()
    { "_id" : 1, "name" : "bob" }
    { "_id" : 2, "name" : "jerry" }
    { "_id" : 3, "name" : "lucy" }
    { "_id" : 4, "name" : "lucyA" }
    { "_id" : ObjectId("5e3a3dc930db5e995f0e0f35"), "name" : "liliBB" }
    { "_id" : ObjectId("5e3a3dc930db5e995f0e0f36"), "age" : 1 }

    2.2 查
    find() findOne() limit() skip() sort()  count()
    db.集合名.find({条件},{字段列表})
    > use bbsdb
    表中搜索所有用户的_id和name字段,_id字段不显示(0),name字段显示(1)
    > db.user6.find({},{_id:0, name:1})
    { "name" : "root" }
    { "name" : "bin" }
    { "name" : "daemon" }
    { "name" : "adm" }
    { "name" : "lp" }
    { "name" : "sync" }

    表中搜索name字段为root的所有信息
    > db.user6.find({name:"root"})

    表中搜索root用户的uid,name,_id信息,只输出uid和name,信息
    > db.user6.find({name:"root"},{uid:1,name:1,_id:0})
    { "name" : "root", "uid" : 0 }

    搜索表中_id字段和name字段的前3条数据,_id字段不显示,name字段显示
    > db.user6.find({},{_id:0, name:1}).limit(3)
    { "name" : "root" }
    { "name" : "bin" }
    { "name" : "daemon" }

    搜索表中_id字段和name字段,跳过前2条输出
    > db.user6.find({},{_id:0, name:1}).skip(2)

    搜索表中_id字段、name字段和uid字段,_id字段不显示,以uid字段升序输出
    > db.user6.find({},{_id:0, name:1,uid:1}).sort({uid:1})

    搜索表中_id字段、name字段和uid字段,_id字段不显示,以uid字段降序输出
    > db.user6.find({},{_id:0, name:1,uid:1}).sort({uid:-1})

    2.3 查询/更新/删除文档的匹配条件
    相等比较  
    > db.集合名.find({字段名:值},{字段值列表})
    搜索表中uid为1的所有数据,不显示_id字段的值
    > db.user6.find({uid:1},{_id:0})
    搜索表中name为root的数据,不显示_id字段的值
    > db.user6.find({name:"root"},{_id:0})
     
    逻辑与比较
    > db.集合名.find({字段名:值,字段名:值},{字段值列表})
    搜索表中name字段为root并且shell字段为"/bin/bash"的数据,不显示_id字段的值
    > db.user6.find({name:"root",shell:"/bin/bash"},{_id:0})
     
    逻辑或比较 $or
    > db.集合名.find({$or:[{条件1},{条件2},{条件3}]},{字段值列表})
    搜索表中uid为1或3或9的数据,只显示name和uid字段
    > db.user6.find({ $or:[{uid:1},{uid:3},{uid:9}] },{_id:0,name:1,uid:1})
    > db.user6.find({ $or:[{uid:1},{name:"bin"},{name:"rsync"}]  },{_id:0,name:1,uid:1})
     
    范围比较 $in  $nin
    > db.集合名.find({字段名:{比较命令:[值列表]}},{字段值列表})
    > db.user6.find({shell:{$nin:["/bin/bash","/sbin/nologin"]}},{_id:0,name:1,shell:1})
    > db.user6.find({uid:{$in:[8,4,7]}},{_id:0,name:1,uid:1})
     
    正则匹配
    name中有"a"的数据
    > db.user6.find({name:/a/},{_id:0,name:1})
    以a或者b开头的
    > db.user6.find({name:/^[ab]/},{_id:0,name:1})
    以d结尾的
    > db.user6.find({name:/d$/},{_id:0,name:1})
     
    数值比较
    $gt $gte  $lt $lte  $ne  
    >   >=      <   <=     !=
    uid > 100的
    > db.user6.find({uid:{$gt:100} },{_id:0,name:1,uid:1} )
    统计uid>100的
    > db.user6.find({uid:{$gt:100} },{_id:0,name:1,uid:1} ).count()
    uid>100升序输出
    > db.user6.find({uid:{$gt:100} },{_id:0,name:1,uid:1} ).sort({uid:1})
    uid>100中的最小值
    > db.user6.find({uid:{$gt:100} },{_id:0,name:1,uid:1} ).sort({uid:1}).limit(1)
    uid在10-20之间
    > db.user6.find({uid:{$gte:10,$lte:20} },{_id:0,name:1,uid:1} )
     
    空 null
    > db.user6.save({name:null,uid:999})
    > db.user6.find({name:null},{_id:0,name:1,uid:1})
     
    2.4 改,更新文档 update()
    db.集合名.update({条件},{字段列表})
    > db.user6.find({uid:{$lte:5}},{_id:0}).count()
    6
    > db.user6.find({uid:{$lte:5}},{_id:0})

    把文档的其他字段都删除了,只留下了修改的字段,且只修改与条件匹配的第1行!!!
    > db.user6.update({uid:{$lte:5}},{password:"AAA"})
    > db.user6.find({uid:{$lte:5}},{_id:0}).count()
    5
    > db.user6.find({uid:{$lte:5}},{_id:0})
    没有root了
    > db.user6.find({password:"AAA"})
    { "_id" : ObjectId("5e397b94727c50e033c960e3"), "password" : "AAA" }

    db.集合名.update({条件},{$set:{字段列表}},false,true)
    $set 条件匹配时,修改指定字段的值
    > db.user6.update({uid:{$lte:5}},{ $set:{password:"FFF",gid:2000}},false,true)
    "name" : "bin", "password" : "FFF", "uid" : 1, "gid" : 2000,
    "name" : "adm", "password" : "FFF", "uid" : 3, "gid" : 2000,
    ...
     
    $unset 删除与条件匹配文档的字段
    > db.user6.find({name:"adm"},{_id:0})
    将password字段删除
    > db.user6.update({name:"adm"},{$unset:{password:"FFF"}})
     
    $inc 条件匹配时,字段值自加或自减
    > db.user6.find({name:"adm"},{_id:0,uid:1})
    { "uid" : 3 }

    > db.user6.update({name:"adm"},{$inc:{uid:11}}) 正数自加
    14
    > db.user6.update({name:"adm"},{$inc:{uid:-1}}) 负数自减
    13

    数组类型的操作命令
    $push $addToSet $pop $pull
    > db.ta.save({name:"bob", like:["a","b","c","d","e"] })
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e" ] }

    > db.ta.update({name:"bob"},{$push:{like:"A"}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e", "A" ] }

    //存在,仍然添加
    > db.ta.update({name:"bob"},{$push:{like:"A"}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e", "A", "A" ] }

    //此方法,存在则不添加
    > db.ta.update({name:"bob"},{$addToSet:{like:"A"}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e", "A", "A" ] }

    //不存在则添加
    > db.ta.update({name:"bob"},{$addToSet:{like:"G"}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e", "A", "A", "G" ] }

    //弹出最外面一个
    > db.ta.update({name:"bob"},{$pop:{like:1}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "a", "b", "c", "d", "e", "A", "A" ] }

    //弹出最里层一个
    > db.ta.update({name:"bob"},{$pop:{like:-1}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "b", "c", "d", "e", "A", "A" ] }

    //将所有的A都删除
    > db.ta.update({name:"bob"},{$pull:{like:"A"}})
    > db.ta.find({name:"bob"},{_id:0})
    { "name" : "bob", "like" : [ "b", "c", "d", "e" ] }
     
    删除文档
    将表中uid<=10的数据全部删除
    > db.user6.remove({uid:{$lte:10}})
    清空user6表
    > db.user6.remove({})

    删除表
    > show tables
    > db.user6.help()
    > db.user6.drop()
     
    三.部署LNMP+MongoDB  192.168.4.50  (mongo-1.6.16.tgz)
    1 安装提供mongo模块软件软件包
    ]# tar -zxvf mongo-1.6.16.tgz
    ]# cd mongo-1.6.16/
    ]# phpize
    ]# ./configure --with-php-config=/usr/bin/php-config
    ]# make
    ]# make install
    ]# ls /usr/lib64/php/modules/mongo.so
    /usr/lib64/php/modules/mongo.so
    ]# ls /usr/lib64/php/modules/
    curl.so      json.so      mongo.so   mysql.so      pdo.so         phar.so   sqlite3.so
    fileinfo.so  mbstring.so  mysqli.so  pdo_mysql.so  pdo_sqlite.so  redis.so  zip.so
     
    2 配置php程序运行时加载模块
    ]# vim /etc/php.ini
     728 extension_dir = "/usr/lib64/php/modules/"
     729 ; On windows:
     730 extension = "redis.so"
     731 extension = "mongo.so"
    :wq
    ]# systemctl restart php-fpm
    ]# php -m | grep -i mongo
    mongo
    ]# php -m | grep -i redis
    redis
     
    3 编写连接mongodb服务的php脚本
    ]# vim  /usr/local/nginx/html/mdb1.php
    <?php
    $m = new Mongo("mongodb://192.168.4.50:27050");
    $db = $m->buysite;
    $c = $db->usera;
    $data=array("name"=>"bob","age"=>19);
    $c->insert($data);
    echo  "data ok";
    ?>
    :wq

    ]# vim /usr/local/nginx/html/mdb2.php
    <?php(直接把源link的php文件集群那行删掉)
    $m = new MongoClient("mongodb://192.168.4.53:27053,192.168.4.52:27052,192.168.4.51:27051");
    $db = $m->db1;
    $c = $db->t15;
    $data=array("name"=>"bob","age"=>19);
    $c->insert($data);
    echo  "data ok";
    ?>
    :wq
     
    4 在客户端访问网站的php脚本(nginx要启动,并配置php连接)
    ]# curl http://localhost/mdb1.php
    data ok
    ]# curl http://localhost/mdb2.php
    data ok

    5 在mongodb服务器本机查看是否存储数据了
    ]# /usr/local/mongodb/bin/mongo --host 192.168.4.50 --port 27050
    > show dbs
    > use buysite
    > db.usera.find()
    { "_id" : ObjectId("5e3a5414e07aecaf1d8b4567"), "name" : "bob", "age" : NumberLong(19) }
     
    ]# /usr/local/mongodb/bin/mongo --host 192.168.4.53 --port 27053
    > show dbs
    > use db1
    > db.t15.find()

  • 相关阅读:
    石油采集
    石油采集
    Redis 笔记与总结7 PHP + Redis 信息管理系统(用户信息的增删改查)
    数据分析电子商务B2C全流程_数据分析师
    数据分析电子商务B2C全流程_数据分析师
    数据挖掘中分类算法小结_数据分析师
    大数据分析或提升企业税务职能价值
    大数据可视化必须避免的三种常见错误
    大数据可视化必须避免的三种常见错误
    数据分析帮你预知商机
  • 原文地址:https://www.cnblogs.com/luwei0915/p/12262293.html
Copyright © 2011-2022 走看看