0

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"},
]
JoeYo
  • 59
  • 9
  • If you specify `... --host mongo ...`, (or even `--host 127.0.0.1`) what happens? – rickhg12hs Aug 01 '23 at 02:26
  • You are using default host and port, thus you can skip them. – Wernfried Domscheit Aug 01 '23 at 05:55
  • 3
    `mongod` starts the database, i.e. the command does not terminate until you shutdown the database. Thus you cannot append any command with `&&`. I am not familiar with docker but I would assume the database is started automatically and already running. – Wernfried Domscheit Aug 01 '23 at 05:58
  • You are right ```--host mongo``` does not work, the reason is the host points to 127.0.0.1 . I did not find this error because second part command did not run at all. – JoeYo Aug 01 '23 at 17:35

1 Answers1

1

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
MrDiggles
  • 748
  • 1
  • 5
  • 19
  • Yea, this works, and it needs to add execution permission to [run this script](https://stackoverflow.com/questions/68476734/docker-entrypoint-initdb-d-bad-interpreter-permission-denied). I removed **Wait** part from this script, the log says **mongo** command does not find... I don't know why. – JoeYo Aug 01 '23 at 17:31
  • According to https://stackoverflow.com/a/74240679/1830312, you may need to use `mongosh` since you're on version 6+ – MrDiggles Aug 11 '23 at 15:07