使用 mongoimport 导入本地 JSON 文件到 MongoDB 及数据查看指南
在项目中,我们经常需要将本地 JSON 文件批量导入 MongoDB 数据库。本文以 Ubuntu 22.04 环境为例,详细记录了如何安装 mongoimport
工具、正确导入多个 JSON 文件,以及查看导入后的数据。
一、环境介绍
操作系统:Ubuntu 22.04.5 LTS
MongoDB 版本:已安装并运行中
目标数据库:
database
目标集合:
instructions
本地 JSON 文件目录:
/home/yhzhao/sun/week1/test_result/
二、安装 mongoimport 工具(bash下)
Ubuntu 22.04 默认源没有 mongo-tools
,需从 MongoDB 官方下载工具包:
wget https://fastdl.mongodb.org/tools/db/mongodb-database-tools-ubuntu2204-x86_64-100.9.4.tgz
tar -zxvf mongodb-database-tools-ubuntu2204-x86_64-100.9.4.tgz
cd mongodb-database-tools-ubuntu2204-x86_64-100.9.4
export PATH=$PATH:$(pwd)/bin
确认安装:
mongoimport --version
三、批量导入 JSON 文件
假设目录中每个 JSON 文件格式是多行独立 JSON 对象,例如:
{ "title": "任务1", "content": "步骤A" }
{ "title": "任务2", "content": "步骤B" }
批量导入命令:
for file in /home/yhzhao/sun/week1/test_result/*.json; domongoimport --db database --collection instructions --file "$file"
done
注意:不要加
--jsonArray
,除非文件是标准 JSON 数组格式。
四、常见问题及解决
错误提示:
Failed: error reading separator after document #1: bad JSON array format - found no opening bracket '[' in input source
产生原因:
用了 --jsonArray
,但 JSON 文件不是数组格式。
解决办法:
去掉 --jsonArray
参数,使用默认方式导入。
五、查看导入数据
进入 MongoDB shell:
mongosh --host localhost:27017
mongosh
选择数据库
use database
查看数据条数:
db.instructions.countDocuments()
查看部分数据:
db.instructions.find().limit(5).pretty()
查看集合列表:
show collections
退出 shell:
exit
六、总结
Ubuntu 22.04 需手动安装 MongoDB Database Tools 来使用
mongoimport
;JSON 文件格式决定是否需要
--jsonArray
参数;结合 Bash 循环批量导入多个文件;
导入成功后,Mongo shell 提供简洁高效的数据查看方式。