如何在Dockerized Mongo DB中初始化集合 [英] How to Initialize a Collection in Dockerized Mongo DB

查看:81
本文介绍了如何在Dockerized Mongo DB中初始化集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我用来对MongoDB实例进行docker化的 docker-compose.yml :

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:

容器已正确创建,并且启动时没有任何问题.可以在容器第一次启动时创建一个Mongo集合并用一些文档填充它吗?

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 } )

...

推荐答案

根据 MongoDB Docker文档,您可以使用此组合来初始化您的数据库:环境变量MONGO_INITDB_DATABASE

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

此变量允许您指定要使用的数据库的名称/docker-entrypoint-initdb.d/*.js中的创建脚本(请参阅在下面初始化一个新实例).MongoDB从根本上讲设计用于首次使用时创建",因此如果您不使用您的JavaScript文件,则不会创建数据库.

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.

和/docker-entrypoint-initdb.d/

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

初始化一个新实例

Initializing a fresh instance

首次启动容器时,它将执行文件带有.sh和.js扩展名/docker-entrypoint-initdb.d.文件将按字母顺序执行命令..js文件将由mongo使用数据库执行由MONGO_INITDB_DATABASE变量指定(如果存在),或者否则测试.您也可以在.js脚本中切换数据库.

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.

请注意,您可以跳过设置环境变量的设置,并在js文件中设置数据库.有关更多说明,请参见文档.

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

希望有帮助.

这篇关于如何在Dockerized Mongo DB中初始化集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆