安装mongodb
centos7安装mongodb
创建/etc/yum.repos.d/mongodb-org-4.0.repo
文件,编辑内容如下:
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc
运行以下命令安装最新版的mongodb:
sudo yum **install** -y mongodb-org
配置mongod.conf
允许远程连接:
vim /etc/mongod.conf # Listen to all ip address bind_ip = 0.0.0.0
启动mongodb:
sudo service mongod start
创建管理员用户:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
启用权限管理:
$ vim /etc/mongod.conf
#security
security:
authorization: enabled
重启mongodb:
sudo service mongod restart
docker安装mongodb
先在本机创建挂载文件夹 ` /data/db 没有权限的话要
sudo 然后
chown -R myname /data`
启动mongodb 不加–auth
docker run --name mymongodb -p 27018:27017 -v /data/db:/data/db -d mongo:3.4
然后进入
docker exec -it mymongodb mongo admin
创建超级用户a
use admin
db.createUser(
{
user: "root",
pwd: "1234",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
删除用户(如果有其他不想要的用户) db.dropUser('chenzhang')
之后重启mongo 并带上–auth
docker stop mymongodb
docker rm mymongodb
docker run --name mymongodb -p 27018:27017 -v /data/db:/data/db -d mongo:3.4 --auth
进入docker
docker exec -it mymongodb mongo admin
登录
use admin
db.auth('root','1234')
用root用户创建其他用户, 用户是跟着库走的, userAdminAnyDatabase权限的用户只有管理用户的权限
use mydb
( 添加用户之前必须use mydb
, 要不然user
的db
是admin
db.createUser(
{
user: "chenzhang",
pwd: "password",
roles: [
{ role: "readWrite", db: "mydb" }
]
}
)
执行show users
能看到当前用户和权限
想查看所有用户
use admin
db.system.users.find()
尝试一下
use mydb
db.auth('chenzhang','password')
处理报错
cursor id not valid at server
pymongo.errors.CursorNotFound: cursor id ‘…’ not valid at server
cursor
超时引起的, 默认for
循环的cursor
10分钟时间存活, 可以设置no_cursor_timeout=True
, 但是要注意最后close
.
cursor=db.images.find({}, {'id':1, 'image_path':1, '_id':0}, , timeout=False)
for i in cursor:
# .....
# .....
cursor.close() # use this or cursor keeps waiting so ur resources are used up
error child process failed exited with error number 48
mongodb启动报错.
处理
# 先杀掉mongod的进程
ps -ef | grep mongod
sudo kill -9 {processid}
# 修复
mongod -f /etc/mongod.conf --repair
# 启动
mongod -f /etc/mongod.conf
mongodb字段字符串类型转整型
db.samples.find({timestamp: {$type: 2}}).forEach(function (doc) {
doc.timestamp = parseInt(doc.timestamp);
db.samples.save(doc);
});