最近学校有个大数据的作业要用到Mongodb,原本以为很快就可以搞定。但用yum安装的Mongodb在用户授权时一直出错,具体问题如下:
[js] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "command listDatabases requires authentication", "code" : 13, "codeName" : "Unauthorized" } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 Mongo.prototype.getDBs@src/mongo/shell/mongo.js:67:1 shellHelper.show@src/mongo/shell/utils.js:876:19 shellHelper@src/mongo/shell/utils.js:766:15 @(shellhelp2):1:1后来在网上找到别的方法解决了用户授权问题。
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.0.2.tgz
tar -zxf mongodb-linux-x86_64-rhel70-4.0.2.tgz
mv mongodb-linux-x86_64-rhel70-4.0.2 /usr/local/mongodb-4.0.2
cd /usr/local/mongodb-4.0.2/
mkdir -p data
mkdir -p log
vim mongo.conf
然后填写如下内容:
#端口号 port=27017 #数据保存路径 dbpath=/usr/local/mongodb-4.0.2/data #日志保存路径 logpath=/usr/local/mongodb-4.0.2/log/mongo.log #设置后台运行 fork=true #日志输出方式 logappend=true #开启认证 auth=true #绑定IP(可以绑定多个IP,例:bindIp: 127.0.0.1,192.33.3.3) bind_ip=0.0.0.0
./bin/mongod --config mongo.conf
./bin/mongo(没有使用用户名和密码)
简单的操作 > use admin switched to db admin > show dbs admin 0.000GB config 0.000GB local 0.000GB >
use admindb.createUser({user:"test",pwd:"test",roles:[{role:"root",db:"admin"}]});
此时创建了用户,但是登录时没有使用用户名和密码,所以之后再使用show dbs会显示没有授权。授权已经在配置文件中配好了,现在只需要退出再登录就可以了。
./bin/mongo -u "test" -p "test" --authenticationDatabase "admin"
授权后就拥有了用户名,此时就可以在例如python程序中连接数据库,并将数据保存在mongodb中。
如果第7步登上去还是显示没有授权,可以使用以下命令:
use admin db.shutdownServer(); exitPs:可能还需要在mongodb文件夹里找到mongod.lock然后
rm -f /usr/local/mongodb/data/db/mongod.lock
退出后再重启服务:./bin/mongod --config mongo.conf
然后再使用:./bin/mongo -u "test" -p "test" --authenticationDatabase "admin"