Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to Execute mongoimport on a Docker Container

Tags:

I use Docker to develop.

docker exec -it <My-Name> mongo

I want to import the data to MongoDB from a JSON file, but it fails.

The command is

mongoimport -d <db-name> -c <c-name> --file xxx.json

What can I do?

like image 439
Chars Davy Avatar asked Apr 18 '18 09:04

Chars Davy


People also ask

How can I access a MongoDB container from another container?

If you need to access the MongoDB server from another application running locally, you will need to expose a port using the -p argument. Using this method, you will be able to connect to your MongoDB instance on mongodb://localhost:27017 . You can try it with Compass, MongoDB's GUI to visualize and analyze your data.

How does MongoDB run in docker container from host?

If your application is running inside a container itself, you can run MongoDB as part of the same Docker network as your application using --network . With this method, you will connect to MongoDB on mongodb://mongodb:27017 from the other containerized applications in the network.


2 Answers

With your description it seems that you have a datafile in json format in your host machine and you want to import this data into mongodb which is running in a container.

You can follow following steps to do so.

#>docker exec -it <container-name> mongo #>docker cp xxx.json <container-name-or-id>:/tmp/xxx.json #>docker exec <container-name-or-id> mongoimport -d <db-name> -c <c-name> --file /tmp/xxx.json 

In the last step you have to use file path that is available in the container.

To debug more if required you can login into the container and execute the way you do on the Linux machines.

#>docker exec -it <container-name-or-id> sh sh $>cat /tmp/xxx.json sh $>mongoimport -d <db-name> -c <c-name> --file /tmp/xxx.json 
like image 98
fly2matrix Avatar answered Sep 20 '22 07:09

fly2matrix


Run without copy file:

docker exec -i <container-name-or-id> sh -c 'mongoimport -c <c-name> -d <db-name> --drop' < xxx.json 
like image 45
Whoiskp Avatar answered Sep 18 '22 07:09

Whoiskp