Search code examples
databasemongodbdockermongoose

How do I import sample data into mongoDB container?


I want to add sample data into mongoDB container when initialize. But when I get into mongdb shell, I am not able to find my collection/table. Did I set anything wrong? How do I pre-load the sample data correctly?

Thanks for any help.

test> show dbs
admin    8.00 KiB
config  12.00 KiB
local    8.00 KiB

Here is part of my docker-compose file.

  mongo:
    image: mongo:7.0-rc
    volumes:
      - ./test/fixtures/mongo:/docker-entrypoint-initdb.d
    command: bash -c "mongod --bind_ip=127.0.0.1 --port=27017 && mongoimport --host mongodb --db sampleDB --collection reviews --file /docker-entrypoint-initdb.d/sample.json --jsonArray"

sample.json file

[
{"id":"a1" , "country":"US"},
{"id":"b2" , "country":"JP"},
]

Solution

  • To echo what @wernfried-domscheit said in the comments, when you run mongod, it does not "complete" until the DB is shut down and so the command after the && will not run (until it's too late).

    An alternative I suggest is to create a script that starts the DB in the background, waits for it be ready, runs the import, and then bring the DB process back into the foreground. I think it would look something like this:

    #!/bin/bash
    
    # Start the mongo process as a background process
    mongod --bind_ip=127.0.0.1 --port=27017 &
    
    # Wait for mongo DB to be ready (see https://stackoverflow.com/a/45060399/1830312)
    until mongo --eval "print(\"waited for connection\")"
      do
        sleep 5
      done
    
    # Run the import
    mongoimport --host mongodb --db sampleDB --collection reviews --file /docker-entrypoint-initdb.d/sample.json --jsonArray
    
    # Wait for all background processes to finish
    wait