首页 > 技术文章 > mongodb运维

mxjhaima 2020-10-23 11:48 原文

创建于2018年,博客搬家后有所改动

安装(linux)

官网下载系统对应版本的mogo压缩包(linux为.tgz),解压即用
https://www.mongodb.com/try/download/community
管理工具使用: MongoBooster,RoboMongo,Rockmongo,studio 3t 推荐使用studio 3t。Rockmongo 是web版的便于远程使用
启动mongo服务:解压后,使用bin/mongod启动mongo服务,mongo默认存储数据路劲/data/db,执行bin/mongod前必须先创建/data/bin,当然可以自定义存储位置。
mongod可以指定参数有:https://www.cnblogs.com/yangliheng/p/6069763.html

启动服务

解压后进入 bin目录 编辑 mongod.conf

dbpath = /data/mongodb      #提前新建/data/mongodb目录
logpath = /data/mongodb/mongodb.log
logappend = true
port = 27017  
fork = true    # 以守护进程的方式运行MongoDB,创建服务器进程
auth =false

执行 ./mongod -f mongod.conf 第一次启动时报错:

about to fork child process, waiting until server is ready for connections.
forked process: 22833
ERROR: child process failed, exited with error number 1
To see additional information in this output, start without the "--fork" option.

关于这个错误,网上解释特别多。 最后一行提示start without the "--fork" option,让你去掉fork选项试试,去掉fork选项后,真正错误的原因暴露出来了(未创建/data/mongodb目录):

2018-05-26T02:17:05 Failed global initialization: FileNotOpen: Failed to open "/data/mongodb/mongodb.log"

链接到mongo

通过mongod -f mongod.conf 启动mongo服务之后,通过bin/mongo命令和mongo进行链接

./mongo    host  [ip]  port    [p]

链接之后日志为:

MongoDB shell version v3.6.20
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("676f927e-e062-4087-a640-5e9fca45f2ae") }
MongoDB server version: 3.6.20

使用help命令

链接到mongodb客户端后,日志提示可以使用help命令

> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, 'global' is default
        use <db_name>                set current database
        db.foo.find()                list objects in collection foo
        db.foo.find( { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell

用户管理和数据库管理

首先需要选项auth =false,创建管理员用户,密码找回,也可以用这种方式

use admin    #选择管理库
db.createUser({user:'admin',pwd:'123456', roles:[{role:'userAdminAnyDatabase', db:'admin'}]})

创建其他的库及用户

use test
db.createUser({user:'test',pwd:'test', roles:[{role:'dbAdmin', db:'test'}]})

用户角色

用户管理中使用了userAdminAnyDatabase角色,mongo中内置其他角色

数据库用户角色:read、readWrite;
数据库管理角色:dbAdmin、dbOwner、userAdmin;
集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
备份恢复角色:backup、restore;
所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
超级用户角色:root // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
内部角色:__system

远程连接

创建好管理员admin用户后,使用链接客户端或者使用 mongo命令 指定IP 连接
发现外网IP死活连接不上,然后就检查机器防火墙,端口号啥的,折腾半天

最后发现需要配置绑定IP,再次编辑mongod.conf,添加bind_ip 配置项

dbpath = /data/mongodb
logpath = /data/mongodb/mongodb.log
logappend = true
port = 27017  
fork = true    # 以守护进程的方式运行MongoDB,创建服务器进程
auth =true    #是否启用密码
bind_ip = ip1,ip2    #改成对应的IP,绑定多个IP用逗号隔开,表示只能从对应的ip 访问。
#特别注意如果你使用的是腾讯云或者其他云产品1.安全组中端口开启,2.绑定ip可能通过ip映射的,绑定时绑定外网ip时直接报错,需要绑定内网ip

启动与停止服务

启动

刚刚其实已经讲过启动服务了,当 fork = true 代表在后台运行,把mongo当做服务挂在服务器上
启动日志:

./mongod -f mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 24241
child process started successfully, parent exiting

停止Mongodb

方法一:查看进程,使用kill命令;不能使用kill -9 (kill -9 容易完犊子,再启动就费劲了)
方法二:在客户端进去,使用shutdown命令

use admin
db.auth("user","pwd")
db.shutdownServer();
server should be down...    #退出日志
2018-05-26T04:49:36.154-0500 I NETWORK  [thread1] trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed    #服务停止后,连接中断

注意这里不是所有的用户都能shutdownServer(),使用前面新建的用户admin是不行的,没有相关权限。
创建一个__system角色的用户,然后使用db.auth("user","pwd")切换到该用户下,再执行db.shutdownServer();

查看当前DB的用户

 show users;

显示为:

{
        "_id" : "admin.admin",
        "user" : "admin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
{
        "_id" : "admin.dba",
        "user" : "dba",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "__system",
                        "db" : "admin"
                }
        ]
}

创建数据库

use DATABASE_NAME  #本身数据库的创建和mysql不同。如果这个数据库中没用户或者数据,这个数据库相当于不存在的。    

http://www.runoob.com/mongodb/mongodb-create-database.html
注意创建数据库时,用户的权限

修改权限、密码

完整格式

db.updateUser(
   "<username>",
   {
     customData : { <any information> },
     roles : [
               { role: "<role>", db: "<database>" } | "<role>",
               ...
             ],
     pwd: "<cleartext password>"
    },
    writeConcern: { <write concern> }
)

如修改权限

db.updateUser('user',{ roles:[{role:'root', db:'admin'}]})

https://www.jianshu.com/p/31c8ba5abab1
https://www.cnblogs.com/yangliheng/p/6069763.html
https://www.cnblogs.com/lemon-le/p/7132038.html
https://blog.csdn.net/u013066244/article/details/53874216
https://www.cnblogs.com/damingge/p/6507605.html

备份与恢复

备份使用bin下的 mongodump命令,mongodump命令有很多参数,具体使用 ./mongodump --help

  • -h MongDB所在服务器地址,例如:127.0.0.1

  • -d 需要备份的数据库实例,例如:test

  • -o 备份的数据存放位置,例如:c:\data\dump,当然该目录需要提前建立,在备份完成后,系统自动在dump目录下建立一个test目录,这个目录里面存放该数据库实例的备份数据。

  • -u 用户

  • -p 密码

  • 备份

./mongodump -h ip:27017 -u admin -p 1ArUNYrVA7kDjD3h -d Sina --out  /data/Sina --authenticationDatabase admin
  • 恢复
./mongorestore   -u admin -p 1ArUNYrVA7kDjD3h  -h ip:27017  --authenticationDatabase admin -d Sina   /data/Sina/Sina

推荐阅读