gpt4 book ai didi

mongodb - 如何在 Dockerized Mongo DB 中初始化集合

转载 作者:行者123 更新时间:2023-12-02 18:11:07 25 4
gpt4 key购买 nike

下面是docker-compose.yml我用来dockerize我的MongoDB实例:

version: '3.3'

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

volumes:
data-storage:

networks:
mynet:

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

例如,我想运行一些这样的语句:
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 documentation ,您可以使用此组合来初始化您的数据库:
环境变量 MONGO_INITDB_DATABASE

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


和/docker-entrypoint-initdb.d/中的 init .js 文件

Initializing a fresh instance

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


请注意,您可以跳过设置环境变量,并在 js 文件中设置您的数据库。见 the doc for more explanations.
希望能帮助到你。

关于mongodb - 如何在 Dockerized Mongo DB 中初始化集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51662531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com