Search code examples
mongodbdockermongoimport

Build a mongo container and import data


I want to build a Mongo container, and insert some data stored in the folder /mongo_mock_data in this container. Here are my lines of code:

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

I have the following error:

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

any ideas what Im doing wrong?

EDIT:

If I try:

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

instead of

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

I have the following error:

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


Solution

  • So, finally, I solved my issue by dropping the argument --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