当前位置: 首页 > 编程文章 >

MongoDB整库与单集合备份还原及数据导入导出指南

MongoDB整库与单集合备份还原及数据导入导出指南

作者:叶川时间:2025-06-27 15:15:51浏览:761

MongoDB提供mongodump和mongorestore工具进行数据库级别的备份与还原,支持通过fsync锁保证数据一致性。对于单个集合或特定字段,可使用mongoexport和mongoimport进行JSON或CSV格式的数据导入导出操作,适用于数据迁移、归档及跨版本兼容场景。

本文目录收起

MongoDB备份原理与fsync锁机制

mongodump.exe 执行备份的核心机制是发起一次查询以获取服务器的当前状态快照,并将其持久化存储至磁盘。由于在捕获快照期间服务器仍可能接收新写入,因此该方式并非绝对实时。为确保备份数据的完整性与安全性,建议结合 fsync 锁指令,强制将内存中的数据刷入缓存后再进行备份操作。


高效开源数据库 MongoDB 的官方下载地址:https://www.jb51.net/softs/41751.html


执行备份前的环境检查示例: > show dbs MyDB 0.0625GB admin (empty) bruce 0.0625GB local (empty) test 0.0625GB > use MyDB switched to db MyDB > db.users.find() { "_id" : ObjectId("4e290aa39a1945747b28f1ee"), "a" : 1, "b" : 1 } { "_id" : ObjectId("4e2cd2182a65c81f21566318"), "a" : 3, "b" : 5 } >

整库备份与还原命令详解

整库备份命令格式: mongodump -h dbhost -d dbname -o dbdirectory 参数说明: -h:指定 MongoDB 服务器地址,如 127.0.0.1,也可包含端口号 127.0.0.1:27017。 -d:指定需要备份的目标数据库实例名称,例如 test。 -o:指定备份文件的存储目录,如 c:\data\dump。需提前创建该目录,备份完成后系统会自动在 dump 目录下生成一个与数据库同名的子目录,其中存放具体的备份数据文件。

mongodump的官方说明(可通过mongodump --help查看):
options:
 --help          produce help message
 -v [ --verbose ]     be more verbose (include multiple times for more
              verbosity e.g. -vvvvv)
 --version        print the program's version and exit
 -h [ --host ] arg    mongo host to connect to ( /s1,s2 for
              sets)
 --port arg        server port. Can also use --host hostname:port
 --ipv6          enable IPv6 support (disabled by default)
 -u [ --username ] arg  username
 -p [ --password ] arg  password
 --dbpath arg       directly access mongod database files in the given
              path, instead of connecting to a mongod server -
              needs to lock the data directory, so cannot be used
              if a mongod is currently accessing the same path
 --directoryperdb     if dbpath specified, each db is in a separate
              directory
 --journal        enable journaling
 -d [ --db ] arg     database to use
 -c [ --collection ] arg collection to use (some commands)
 -o [ --out ] arg (=dump) output directory or "-" for stdout
 -q [ --query ] arg    json query
 --oplog         Use oplog for point-in-time snapshotting
 --repair         try to recover a crashed database
 --forceTableScan     force a table scan (do not use $snapshot)

整库恢复命令格式: mongorestore -h dbhost -d dbname –directoryperdb dbdirectory 参数说明: -h:MongoDB 服务器地址。 -d:指定恢复目标数据库实例名,可与备份时不同(如备份为 test,恢复时可命名为 test2)。 –directoryperdb:指定备份数据所在的源目录路径,例如 c:\data\dump\test。此处路径结构需对应备份时的层级。 –drop:可选参数,表示在恢复前删除当前数据库中的现有数据。这意味着恢复后,备份时间点之后新增或修改的数据将被清除,使用时需谨慎评估。

mongorestore的官方说明(可通过mongorestore --help查看):
options:
 --help         produce help message
 -v [ --verbose ]    be more verbose (include multiple times for more
             verbosity e.g. -vvvvv)
 --version        print the program's version and exit
 -h [ --host ] arg    mongo host to connect to ( /s1,s2 for sets)
 --port arg       server port. Can also use --host hostname:port
 --ipv6         enable IPv6 support (disabled by default)
 -u [ --username ] arg  username
 -p [ --password ] arg  password
 --dbpath arg      directly access mongod database files in the given
             path, instead of connecting to a mongod server -
             needs to lock the data directory, so cannot be used
             if a mongod is currently accessing the same path
 --directoryperdb    if dbpath specified, each db is in a separate
             directory
 --journal        enable journaling
 -d [ --db ] arg     database to use
 -c [ --collection ] arg collection to use (some commands)
 --objcheck       validate object before inserting
 --filter arg      filter to apply before inserting
 --drop         drop each collection before import
 --oplogReplay      replay oplog for point-in-time restore
 --oplogLimit arg    exclude oplog entries newer than provided timestamp
             (epoch[:ordinal])
 --keepIndexVersion   don't upgrade indexes to newest version
 --noOptionsRestore   don't restore collection options
 --noIndexRestore    don't restore indexes
 --w arg (=1)      minimum number of replicas per write

单个集合数据导出与导入方法

单个 Collection 备份命令: mongoexport -h dbhost -d dbname -c collectionname -f collectionKey -o dbdirectory 参数说明: -h:MongoDB 服务器地址。 -d:指定操作的数据库实例。 -c:指定需要导出的集合(Collection)名称。 -f:指定需要导出的具体字段列表,若省略则导出所有字段。 -o:指定输出文件的文件名。

mongoexport的官方说明(可通过mongoexport --help查看):
 --help          produce help message
 -v [ --verbose ]     be more verbose (include multiple times for more
              verbosity e.g. -vvvvv)
 --version         print the program's version and exit
 -h [ --host ] arg     mongo host to connect to ( /s1,s2 for
              sets)
 --port arg        server port. Can also use --host hostname:port
 --ipv6          enable IPv6 support (disabled by default)
 -u [ --username ] arg   username
 -p [ --password ] arg   password
 --dbpath arg       directly access mongod database files in the given
              path, instead of connecting to a mongod server -
              needs to lock the data directory, so cannot be used
              if a mongod is currently accessing the same path
 --directoryperdb     if dbpath specified, each db is in a separate
              directory
 --journal         enable journaling
 -d [ --db ] arg      database to use
 -c [ --collection ] arg  collection to use (some commands)
 -f [ --fields ] arg    comma separated list of field names e.g. -f
              name,age
 --fieldFile arg      file with fields names - 1 per line
 -q [ --query ] arg    query filter, as a JSON string
 --csv           export to csv instead of json
 -o [ --out ] arg     output file; if not specified, stdout is used
 --jsonArray        output to a json array rather than one object per
              line
 -k [ --slaveOk ] arg (=1) use secondaries for export if available, default
              true
 --forceTableScan     force a table scan (do not use $snapshot)

单个 Collection 恢复命令: mongoimport -d dbhost -c collectionname –type csv –headerline –file 参数说明: -type:指定导入文件的格式类型(如 csv、json 等)。 -headerline:标识第一行为列名头信息,导入时将跳过该行数据。 -file:指定待导入数据文件的具体路径。

mongoimport的官方说明(可通过mongoimport --help查看):
 --help         produce help message
 -v [ --verbose ]    be more verbose (include multiple times for more
             verbosity e.g. -vvvvv)
 --version        print the program's version and exit
 -h [ --host ] arg    mongo host to connect to ( /s1,s2 for sets)
 --port arg       server port. Can also use --host hostname:port
 --ipv6         enable IPv6 support (disabled by default)
 -u [ --username ] arg  username
 -p [ --password ] arg  password
 --dbpath arg      directly access mongod database files in the given
             path, instead of connecting to a mongod server -
             needs to lock the data directory, so cannot be used
             if a mongod is currently accessing the same path
 --directoryperdb    if dbpath specified, each db is in a separate
             directory
 --journal        enable journaling
 -d [ --db ] arg     database to use
 -c [ --collection ] arg collection to use (some commands)
 -f [ --fields ] arg   comma separated list of field names e.g. -f name,age
 --fieldFile arg     file with fields names - 1 per line
 --ignoreBlanks     if given, empty fields in csv and tsv will be ignored
 --type arg       type of file to import. default: json (json,csv,tsv)
 --file arg       file to import from; if not specified stdin is used
 --drop         drop collection first
 --headerline      CSV,TSV only - use first line as headers
 --upsert        insert or update objects that already exist
 --upsertFields arg   comma-separated fields for the query part of the
             upsert. You should make sure this is indexed
 --stopOnError      stop importing at first error rather than continuing
 --jsonArray       load a json array, not one item per line. Currently
             limited to 16MB.

其他常见的导入与导出操作示例:

常用导入导出操作示例分析

1. 使用 mongoimport 导入数据: mongoimport -d my_mongodb -c user user.dat 参数解析: -d:指定目标数据库,本例中为 “my_mongodb”。 -c:指定目标集合,本例中为 “user”。 注意:在执行导入操作时,如果指定的集合不存在,系统会自动隐式创建该表结构。

2. 使用 mongoexport 导出数据: mongoexport -d my_mongodb -c user -o user.dat 参数解析: -d:指定源数据库,本例中为 “my_mongodb”。 -c:指定源集合,本例中为 “user”。 -o:指定输出文件名,本例中为 “user.dat”。 从上述命令可见,默认情况下 mongoexport 输出的数据格式为 JSON 样式。

上一篇
MongoDB常见启动错误与解决方法汇总

本文总结了MongoDB在配置、启动及服务安装过程中常见的错误现象与解决方案。主要涵盖因存储引擎从mmapv1切换至wiredTiger导致的rc:100错误,非正常关闭产生的mongod.lock锁定问题,以及dbpath权限不足和bind地址限制等配置失误。此外,还详细记录了Windows环境下重装服务时出现的地址错误及1607异常的排查步骤,为快速恢复数据库服务提供参考思路。

下一篇
MongoDB查询中projection限制返回字段详解

MongoDB的projection机制用于控制find()查询结果中返回的文档字段。默认情况下_id字段会被包含,可通过指定{field:1}包含特定字段或{field:0}排除字段。除_id外,不能在同一projection中混合使用包含和排除逻辑。对于数组字段,需借助$elemMatch或$slice运算符进行投影操作。

相关文章

更多
MongoDB 数据库备份、还原与数据导入导出操作指南

本文介绍 MongoDB 中用于数据迁移和备份的四个核心工具:mongodump、mongorestore、mongoexport 和 mongoimport。mongodump 和 mongorestore 基于 BSON 格式进行库级备份与还原,支持全库或指定库操作;mongoexport 和 mongoimport 则针对表级数据,支持 JSON、CSV 等格式,可精确控制字段与查询条件。这些工具适用于电商系统等场景下的数据库升级与数据迁移任务。

2025.10.27 933
基于PHPExcel实现数据库数据导入导出及筛选功能

本文介绍如何使用PHPExcel库处理数据库数据的导入与导出操作。通过具体代码示例,展示如何将数据库记录写入Excel文件以及如何从Excel读取并筛选数据,帮助开发者快速实现相关功能。

2026.09.06 686

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。