MongoDB的安装
MongoDB官网下载地址 下载安装包并解压到mongo/
创建mongo/db目录和/mongo/log/mongodb.log文件
创建配置文件mongo/mongodb.conf
# 数据文件存放目录 dbpath=/Users/youyou-2608/Downloads/mongodb/db # 日志文件存放目录 logpath=/Users/youyou-2608/Downloads/mongodb/log/mongodb.log # 以追加的方式记录日志 logappend=true # 默认端口27017 port=27017 # 对访问ip地址不做限制,默认为本地地址 bind_ip=0.0.0.0 # 以守护进程的方式启用,即在后台运行 fork=true # 默认开启身份认证 auth=true
配置环境变量及服务的启动和停止
~/.bash_profile文件中:
export PATH = mongo/bin:$PATH
执行 sourcce ~/.bash_profile
启动及停止:
# 启动
mongod -f mongo/mongodb.conf
# 停止
kill 9 -pid
use amdin;
db.shutdownServer();
关闭MongoDB报错:
Error: shutdownServer failed: {
“ok” : 0,
“errmsg” : “not authorized on admin to execute command { shutdown: 1.0, lsid: { id: UUID("4d11f7c3-3b79-458d-b857-2aac4816cd17") }, $db: "admin" }”,
“code” : 13,
“codeName” : “Unauthorized”
}
因为没有 hostManager 权限所以报错:
use admin;
db.grantRolesToUser("uadd", [{role: "hostManager", db: "admin"}]);
# 授权后再执行
db.shutdownServer()
登录认证
登录及创建用户:
> use admin;
> db.auth("uadd", "uadd")
use admin;
# 创建管理员用户
db.createUser(
{
"user": "testuser",
"pwd": "123456",
"roles": [
{
"role": "userAdminAnyDatabase",
"db": "admin"
}
]
}
)
# 创建普通用户
use test;
db.createUser(
{
"user": "testuser",
"pwd": "123456",
"roles": [
{
"role": "readWrite",
"db": "test"
}
]
}
)
增删改查及常用命令
use database;
show dbs;
show users;
db.user.insert({"name": "zhangsan"});
db.user.insertMany([]);
db.user.deleteOne({"name": "zhangsan"})
db.user.deleteMany("_id": {"$gte": 3})
db.user.find("age": {"$gte": 3, "$lte": 20})
db.user.drop();