构建 mongo 容器并导入数据

Build a mongo container and import data

我想建一个Mongo容器,把/mongo_mock_data文件夹下的一些数据插入到这个容器里。这是我的代码行:

MONGO_ID=$(docker run --publish-all -d --mount type=bind,source=${PWD}/mongo_mock_data,target=/tmp/mongo_mock_data mongo)
MONGO_PORT=$( docker inspect $MONGO_ID |  jq -r '.[0].NetworkSettings.Ports."27017/tcp"[0].HostPort' )
MONGODB_URL=mongodb://localhost:${MONGO_PORT}
docker exec $MONGO_ID mongoimport --host $MONGODB_URL --db algo --collection train --type json --file /tmp/mongo_mock_data/train_data.json --jsonArray
docker exec $MONGO_ID mongoimport --host $MONGODB_URL --db algo --collection calculation --type json --file /tmp/mongo_mock_data/predict_data.json --jsonArray
docker exec $MONGO_ID mongoimport --host $MONGODB_URL --db algo --collection train --type json --file /tmp/mongo_mock_data/cluster_data.json --jsonArray

我有以下错误:

error parsing command line options: error parsing URI from mongodb:///localhost:32773/?replicaSet=mongodb:: error parsing uri: must have at least 1 host

知道我做错了什么吗?

编辑:

如果我尝试:

MONGODB_URL=localhost:${MONGO_PORT}
docker exec $MONGO_ID mongoimport --host $MONGODB_URL --db pulse_algo --collection train --type json --file /tmp/mongo_mock_data/train_data.json --jsonArray

而不是

MONGODB_URL=mongodb://localhost:${MONGO_PORT}
docker exec $MONGO_ID mongoimport --host $MONGODB_URL --db algo --collection train --type json --file /tmp/mongo_mock_data/train_data.json --jsonArray

我有以下错误:

error connecting to host: could not connect to server: server selection error: server selection timeout

mongodb:/// 中的第三个斜杠是转录错误吗?如果没有,那么发生的事情是 MongoDB 正在尝试连接到位于 '' 的服务器(即 nothing)到名为 [=12= 的数据库],而不是位于 localhost:32773 和默认数据库的服务器。

所以,最后,我通过删除参数 --host:

解决了我的问题
MONGO_ID=$(docker run --publish-all -d --mount type=bind,source=${PWD}/mongo_mock_data,target=/tmp/mongo_mock_data mongo)
MONGO_PORT=$( docker inspect $MONGO_ID |  jq -r '.[0].NetworkSettings.Ports."27017/tcp"[0].HostPort' )
docker exec $MONGO_ID mongoimport --db algo --collection train --type json --file /tmp/mongo_mock_data/train_data.json --jsonArray
docker exec $MONGO_ID mongoimport --db algo --collection calculation --type json --file /tmp/mongo_mock_data/predict_data.json --jsonArray
docker exec $MONGO_ID mongoimport --db algo --collection train --type json --file /tmp/mongo_mock_data/cluster_data.json --jsonArray

在我的例子中,我收到此错误是因为将选项 --csv 而不是 --type=csv 传递给 mongoexport。更正此问题已解决。

mongoexport type options

错误信息本来可以更好。