How to seed data into Mongo with Docker

Here is how to import initial data into Mongo running on Docker. You need 3 files to edit / create for it.

  • docker-compose.yml
  • init.sh (Mongo importing script)
  • data.json (actual data imported)

Docker Compose

You can use environment variables: DB_USER, DB_PASSWORD, DB_PORT in like .env.
In this example, as imported data is in /db/init/data.json, the volumes parameter has the path. If you use Mongo on Docker, docker-entrypoint-initdb.d directory is the default execution location.

version: '3.7'

services:
  mongo:
    image: mongo:latest
    restart: always
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${DB_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${DB_PASSWORD}
    ports:
      - ${DB_PORT}:${DB_PORT}
    volumes:
      - ./db/init:/docker-entrypoint-initdb.d

Importing script (init.sh)

Add mongoimport command here.

mongoimport --db <your_db_name> --collection <your_collection_name> --drop --file /docker-entrypoint-initdb.d/data.json --jsonArray

Data file (data.json)

Finally, here is the actual data imported. Defined in the docker-compose.yml, the data file will be mapped to /docker-entrypint-initdb.d/data.json.

[
  { "name": "NAME 1", "email": "EMAIL 1" },
  { "name": "NAME 2", "email": "EMAIL 2" },
]

That's it. After compose-up, you can see the seed data in the database using Mongo Compass.