【Linux】Mongodb常用命令

docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
services:
mongo:
image: mongo:8.0.9
container_name: mongo-wordswar
ports:
- "39090:27017"
volumes:
- ./mongo_data:/data/db
- ./log:/var/log
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: 123456
1
2
# 进入容器里的mongodb
docker exec -it <容器名称或ID> mongosh -u 用户名 -p 密码 --authenticationDatabase admin

备份指定数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
# 先备份在docker容器中
mongodump -db fantasy_main --gzip --archive=/tmp/fantasy_main.gz
# 再将其迁移出来
docker cp mongo:/tmp/fantasy_main.gz /home/ubuntu/fantasy_main.gz

# 完整命令
docker exec -it mongo-wordswar-dev mongodump -u admin -p 123456 --authenticationDatabase admin --db fantasy_main --gzip --archive=/tmp/fantasy_main_$(date +%Y%m%d_%H%M%S).gz

# 展示容器中有哪些文件
docker exec -it mongo-wordswar-dev ls -lh /tmp
-rw-r--r-- 1 root root 588K Jun 26 09:39 fantasy_main_20260626_173923.gz
# 将文件放到linux中
docker cp mongo-wordswar-dev:/tmp/fantasy_main_20260626_173923.gz .

将数据库恢复到服务器

1
2
3
4
5
6
# 先将数据放到docker容器中
docker cp fantasy_main.gz mongo:/tmp/fantasy_main.gz
# 恢复,注意:!!!!带--drop表示完全恢复到当时的状态,这段时间的修改和新创建的用户都会丢失
mongorestore --drop --gzip --archive=/tmp/fantasy_main.gz
# docker用法
docker exec -it mongo mongorestore -u admin -p 123456 --authenticationDatabase admin --drop --gzip --archive=/tmp/fantasy_main_dev_20260626_173923.gz

数据库操作

1
2
3
4
5
6
7
8
9
# 展示数据库
test> show dbs
admin 100.00 KiB
config 108.00 KiB
fantasy_main 305.12 MiB
local 72.00 KiB

# 进入数据库
use fantasy_main

集合操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 展示集合
fantasy_main> show collections
Account
ActivateUnit
MailBox
MailComponent
MailUnit

# 查看集合中的所有索引
db.Account.getIndexes()
# 输出
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]

# 创建索引
db.Account.createIndex({ Openid: 1 }, { unique: true })

# 显示集合中有多少个元素
db.Account.countDocuments()