在 Ubuntu 上导入 MongoDB 数据,常见有几种方式,取决于你已有的数据格式(.json、.csv、.bson 等)。下面按最常用场景说明。
例如 data.json:
{ "name": "Tom", "age": 20 }
{ "name": "Jerry", "age": 18 }
(注意:MongoDB 导入要求 每行一个 JSON 对象,不是 JSON 数组)
mongoimportmongoimport \
--db test \
--collection users \
--file data.json \
--jsonArray
如果是数组格式(推荐加 --jsonArray):
[
{ "name": "Tom", "age": 20 },
{ "name": "Jerry", "age": 18 }
]
命令:
mongoimport --db test --collection users --file data.json --jsonArray
假设 data.csv:
name,age
Tom,20
Jerry,18
命令:
mongoimport \
--db test \
--collection users \
--type csv \
--headerline \
--file data.csv
如果你是恢复备份:
mongorestore --db test dump/test
恢复全部:
mongorestore dump/
mongoimport \
--host localhost \
--port 27017 \
--username admin \
--password yourpassword \
--authenticationDatabase admin \
--db test \
--collection users \
--file data.json
新版本 MongoDB 已分离工具:
sudo apt install mongodb-database-tools
❌ command not found: mongoimport
✅ 安装 mongodb-database-tools
❌ JSON 格式错误
✅ 确保是 每行一个对象 或使用 --jsonArray
如果你能告诉我:
我可以给你精确命令。