在 CentOS 上向 MongoDB 导入数据,常见方法有以下几种,根据你的数据格式选择即可。
mongoimport 导入(最常用)CentOS 通常 MongoDB 安装后自带 mongoimport,如果提示命令不存在:
# MongoDB 6+ 需要单独安装工具包
sudo yum install mongodb-database-tools
假设有 data.json:
{ "name": "Tom", "age": 20 }
{ "name": "Jerry", "age": 18 }
导入命令:
mongoimport \
--host 127.0.0.1 \
--port 27017 \
--db testdb \
--collection users \
--file data.json \
--jsonArray
--jsonArray:如果是 JSON 数组格式[ {...}, {...} ]才加
mongoimport \
--db testdb \
--collection users \
--type csv \
--headerline \
--file data.csv
--headerline:第一行作为字段名mongoimport \
--host 127.0.0.1 \
--port 27017 \
--username admin \
--password yourpass \
--authenticationDatabase admin \
--db testdb \
--collection users \
--file data.json
mongorestore 导入(备份恢复)适用于 mongodump 导出的数据
mongorestore \
--host 127.0.0.1 \
--port 27017 \
--db testdb \
/backup/testdb
带账号密码:
mongorestore \
--username admin \
--password yourpass \
--authenticationDatabase admin \
--db testdb \
/backup/testdb
mongo testdb
db.users.insertMany([
{ name: "Tom", age: 20 },
{ name: "Jerry", age: 18 }
])
command not found: mongoimport
→ 安装 mongodb-database-tools
mongod 是否启动bindIpsystemctl status mongod
如果你能告诉我:
我可以给你更精确的命令。