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?
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.
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.
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
Run without copy file:
docker exec -i <container-name-or-id> sh -c 'mongoimport -c <c-name> -d <db-name> --drop' < xxx.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With