系统运作时常发生在特定环境才会出错的问题,其他环境又没发生,我们通常会需要该环境的资料来想办法重现问题。
有这需求时,第一时间当然是想直接透过 GUI 方式(环境允许的话)进行汇入汇出。於是我试了 MongoDB Compass
,点选上方的 Collection
-> Export Collection
就能够有方便的操作罗!
你以为事情结束就太简单了,因为 MongoDB 储存的资料格式终究是 bson
而非罗盘提供的 json
、csv
,有经验的人已经想到会发生什麽事情了,没错,就是 Import(restore)。
在某些栏位型别会发生不可预期的转型错误,反正你就是汇不进去了、也没辄了。
所以一切还是回到原点,使用官方提供的指令来吧
mongodump
资料汇出的指令。常用的参数设定有:
mongodump --host="127.0.0.1:27017" -u root -p pass.123 --authenticationDatabase=admin -d=i18n -c=localization --query "{ \"Data.DateCreated.0\": { \"\$gte\": 637501248000000000 \"\$lt\": 637502112000000000 }}" -o="/tmp/mongodump/"
我指令通常还会加上压缩,比较方便传输
--gzip
通常操作这个动作,目的是尽量不要影响线上运行的资料库,所以会针对次要节点去操作,不去影响主节点的写入效能。
--readPreference=secondary
针对 replica set
、sharded
都有特别参数,可以查看help 或官网,这边就不再一一描述。
mongodump --help
通常是停止对外服务的时候(也就是maintenance啦~)会这样操作,避免汇入汇出资料会有问题,例如同时写入、效能等。
锁定:
db.fsyncLock()
解锁:
db.fsyncUnlock()
这边比较特别的是上锁有次数的概念,可以看到下图我连续输入两次指令,回应的lockCount
内变化。
而解锁也是需要有相同的解锁次数,如果我只输入一次,lockCount
仍然还有 1
喔!所以该值要等於 0
才会完全解锁
mongorestore
资料汇入的指令。汇入就简单多了,设定好帐密、目标以及资料来源即可啦~
mongorestore --host="127.0.0.1:27017" -u root -p pass.123 --authenticationDatabase=admin -d=i18n /tmp/mongodump
dump、restore 还有其他相关的参数,我就不再一一讲述了,文末会放上官网连结,或者可以使用 --help
查看。
觉得指令版本不好用,也有 bash 版本
因为 dump 指令只能一次一个 collection,加上如果有定期备份特定 collection 的需求,因此写了个 bash 来省事:
也顺便放上 gist
#!/bin/bash
host=127.0.0.1
port=27017
authDB=admin
db=[YourDB]
user=root
pwd=[YourPassword]
collections="[Collection1] [Collection2]"
output_folder="./export/"
for collection in $collections; do
echo $collection
mongodump --host $host --port $port -u $user -p $pwd --authenticationDatabase $authDB --collection $collection --db $db --out ${output_folder}
done
error connecting to host: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
这个通常是
--authenticationDatabase=admin
the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
building a list of collections to restore from /tmp/mongodump dir
don't know what to do with subdirectory "mongodump/xxx", skipping...
0 document(s) restored successfully. 0 document(s) failed to restore.
这个通常是来源路径错了,请检查 /tmp/mongodump
底下是否有 bso n 以及 json 档案,汇出时通常会多一层 database 资料夹,以我上面的例子,完整路境应该是 /tmp/mongodump/xxx
Reference:
本系列文章会同步发表於我个人的部落格 Pie Note
<<: [2021铁人赛 Day11] General Skills 08
Transition 使用 昨天讲到元素的变形,而今天的 Transition 就是使用在元素改变时...
终於,这天还是来了,是时候该做个了结,基於纯粹的好奇跟想炫技,想要认识Windows把她改造成自己喜...
Python 中的字串和串列有很多相似的性质,可以想成字串是元只能是字元的串列 所以可以用索引和 S...
哈罗!昨天使用 SWR 实作了一个小功能,让使用者可以列出某 Github user 的所有公开 r...
今天要把「关於」的部分写完 首先因为架构是差不多的,所以我打算使用json做成文档然後再抓取渲染 先...