How to Initialize a Collection in Dockerized Mongo DB

余生长醉 提交于 2020-12-10 07:44:21

问题


Here below is the docker-compose.yml I use to dockerize my MongoDB instance:

version: '3.3'

services:
  mongo:
    image: 'mongo:latest'
    ports:
      - '27017:27017'
    volumes:
      - 'data-storage:/data/db'
    networks:
      mynet:

volumes:
  data-storage:

networks:
  mynet:

The container is created correctly and it starts without any problem. Is it possible to create a Mongo collection and populate it with some documents the first time the container starts?

For instance, I'd like to run a few statements like these:

db.strategyitems.insert( { symbol: "chf", eval_period: 15, buy_booster: 8.0, sell_booster: 5.0, buy_lot: 0.2, sell_lot: 0.2 } )
db.strategyitems.insert( { symbol: "eur", eval_period: 15, buy_booster: 8.0, sell_booster: 5.0, buy_lot: 0.2, sell_lot: 0.2 } )
db.strategyitems.insert( { symbol: "usd", eval_period: 15, buy_booster: 8.0, sell_booster: 5.0, buy_lot: 0.2, sell_lot: 0.2 } )

...


回答1:


According to the MongoDB docker documentation, you can use this combination to init your db : Environnement variable MONGO_INITDB_DATABASE

This variable allows you to specify the name of a database to be used for creation scripts in /docker-entrypoint-initdb.d/*.js (see Initializing a fresh instance below). MongoDB is fundamentally designed for "create on first use", so if you do not insert data with your JavaScript files, then no database is created.

And init .js files in /docker-entrypoint-initdb.d/

Initializing a fresh instance

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

Note that you can skip setting environnement variable, and set your database in js file. See the doc for more explanations.

Hope it helps.



来源:https://stackoverflow.com/questions/51662531/how-to-initialize-a-collection-in-dockerized-mongo-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!