最近在导入MongoDB数据时遇到一个错误:
[root@]# mongorestore --host 127.0.0.1 --port 27017 --username xxx --password xxx --authenticationDatabase admin --db xxx --dir xxxx
2024-04-21T19:56:21.615+0800 building a list of collections to restore from xxx dir
2024-04-21T19:56:21.616+0800 Failed: restore error: ant.files: error reading database: not authorized on xxxx to execute command { listCollections: 1, cursor: { batchSize: 0 } }
出现这种情况是因为,admin库的用户没有足够权限恢复数据到指定库,可以给用户增加MongoDB内置角色restore。
MongoDB备份和恢复角色:
admin数据库包含下列角色用来备份和恢复数据
backup:提供最小的备份数据的权限,该角色提供了足够的权限用于:MongoDB cloud manager 备份代理、ops manager 备份代理或者用于mongodump备份整个mongod实例
restore:提供权限用来从备份恢复数据,但是不包括system.profile集合数据。此角色提供了足够的权限用于使用不带–oplogReplay选项的mongorestore恢复数据
使用下面代码更新用户角色:
db.updateUser( "MyUserAdmin",
{ roles : [
{ role : "restore", db : "admin" },
{ role : "backup", db : "admin" }
] } )
更新完成后即可正常恢复数据到指定库。