Set the username and password of the MongoDB database
/etc/xxx.conf
Edit mongodb configuration file to enable user authentication
vim /etc/mongodb.conf
# IP
bind_ip = 0.0.0.0
# 端口
port = 27017
Modify the following security configuration
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
Remove #auth=true
comments before#
auth = true
Restart mongodb
Service
service mongodb restart
mongo
Connect to the server using a shell
# 连接服务器
mongo
# 连接到 admin 数据库
use admin
# 创建管理员账号,用户名和密码可以任意,角色为 `root`
db.createUser({user:'root',pwd:'123456',roles:['root']})
# 登录
db.auth('root','123456')
After login in the admin database
user admin
db.auth('root','hello')
show collections
> system.users
> system.version
# 显示用户信息
db.system.users.find().pretty()
Design user name and password for a specific database
# 创建数据库
use hr
# 创建用户
db.createUser({
user:'hr_user',
pwd:'123',
roles:[{db:'hr',role:'dbOwner'}]
})
# 显示用户
show users
Connect to the database
mongo 127.0.0.1:27017/demo -u demo -p
# 获得 mongo shell 更多信息
mongo --help
Data modeling
文档
Embedded in子文档
- Between documents
引用
($lookup
similar to table connections in a relational database)
MongoDB a document cannot exceed 16M (a document should not be nested too large)
MongoDB GridFS (Grid File System)
Used to store large files (more than 16M), the file (default) will be cut into 255k block storage, stored in two sets, one stores the meta information of the file, the other stores the data
# 往数据库 myfile 中上传(put)文件
mongofiles -d myfile put 文件路径
# 显示数据库 myfile 中的文件
mongofiles -d myfile list
Files are stored in two collections
- Metadata information of the fs.files file (file name, size, block size, date, _id)
- The content of the fs.chunks file (files_id, content, format)
mongofiles
Upload to remote database
mongofiles -h ip -d db_name -u user -p password put file_path
mongofiles -h ip -d db_name -u user -p password list
mongofiles
Tools are command line development tools