mongodb 笔记

启动mongodb(window)

首先添加环境变量

在安装mongodb的盘的根目录下新建data目录,如 C:/data
在终端命令行下进入

1
cd C:

运行mongodb

1
mongod

连接mongodb

1
mongo

启动mongodb(linux)

首先进入mongodb的bin目录

1
cd /usr/local/mongodb/bin

运行mongodb

1
./mongod

用户管理

使用mongod启动默认是没有开启鉴权的,连接mongodb也不需要账号和密码。

创建新用户

创建用户需要先连接admin, 使用db.createUser()方法添加新用户:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// addUser.js
var db = connect('admin');
db.createUser({
user:"tom",
pwd:"123456",
customData:{
name:'tom',
email:'abc123@163.com',
age:18,
},
roles:[
{
role: 'readWrite',
db: 'test'
}
]
})

1
2
use admin
load('addUser.js')

返回 true, 表示新建成功
查看所有用户

1
db.system.users.find({})

修改用户信息

下面是修改用户 tom 的 db 字段,将默认的 admin 修改为 test

1
db.system.users.update({user: 'tom'}, {$set: {db: 'test'}})

删除用户

下面是删除用户 tom, 删除成功后查找无结果

1
db.system.users.remove({user: 'tom'})

启用验证

添加身份验证

db.auth() 允许用户从shell中对数据库进行身份验证

1
db.auth( <username>, <password> )

返回:db.auth()返回0时,验证未成功,返回1时,操作成功。

注意: 该mongo壳排除所有db.auth()从已保存的历史操作。
即按键盘的 ↑ 不会再次出现输入过的 db.auth 命令

启动mongodb时验证

可以在启动mongod时添加 --auth 参数
如果已经开启了mongod, 需要先关闭:

1
db.shutdownServer()

重新启动

1
mongod --auth

可以从下面的启动信息看到验证已开启, 再次连接mongodb时需要验证用户名和密码了

也可以在mongodb.conf添加参数 auth = true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#端口号
port = 27017
pidfilepath = /data/mongodb/mongo.pid
#数据目录
dbpath = /data/mongodb/data/db
#日志目录
logpath = /data/mongodb/data/logs/mongodb.log
bind_ip = 0.0.0.0
#设置后台运行
fork = true
#日志输出方式
logappend = true
#开启认证
auth = true

linux 启动:

1
2
cd /usr/local/mongodb/bin
./mongod -f /data/mongodb/mongodb.conf

linux 关闭 mongodb:

1
ps aux|grep mongod
1
2
root      2146  0.2  5.7 991040 58208 ?        Sl   00:24   1:48 ./mongod -f /data/mongodb/mongodb.conf
root 7891 0.0 0.0 112660 968 pts/0 R+ 11:37 0:00 grep --color=auto mongod
1
kill -2 2146