首页 > 解决方案 > 将json中的数据导入mongo容器docker

问题描述

我有个问题。我开始学习docker。我知道如何创建一个容器,现在我尝试将数据(json)导入我的容器 mongo,但我不知道如何做到这一点。你能帮助我并为此提供一个简单的解决方案吗?使用 Docker-compose。

我的容器 - mongo 我的文件 - data.json

谢谢!

标签: dockerdocker-compose

解决方案


您不能简单地使用 docker-compose 导入 JSON。您需要将数据放在 js 文件中并js使用/docker-entrypoint-initdb.d

当一个容器第一次启动时,它将执行带有扩展名的文件,.sh这些文件.js位于 /docker-entrypoint-initdb.d. 文件将按字母顺序执行。.js文件将由 mongo 使用由MONGO_INITDB_DATABASE变量指定的数据库执行(如果存在),否则进行测试。您还可以在.js脚本中切换数据库。

mongo 初始化一个新的实例

示例 js 文件:

db = db.getSiblingDB("test");
db.article.drop();

db.article.save( {
    title : "this is my title" , 
    author : "bob" , 
    posted : new Date(1079895594000) , 
    pageViews : 5 , 
    tags : [ "fun" , "good" , "fun" ] ,
    comments : [ 
        { author :"joe" , text : "this is cool" } , 
        { author :"sam" , text : "this is bad" } 
    ],
    other : { foo : 5 }
});

db.article.save( {
    title : "this is your title" , 
    author : "dave" , 
    posted : new Date(4121381470000) , 
    pageViews : 7 , 
    tags : [ "fun" , "nasty" ] ,
    comments : [ 
        { author :"barbara" , text : "this is interesting" } , 
        { author :"jenny" , text : "i like to play pinball", votes: 10 } 
    ],
    other : { bar : 14 }
});

db.article.save( {
    title : "this is some other title" , 
    author : "jane" , 
    posted : new Date(978239834000) , 
    pageViews : 6 , 
    tags : [ "nasty" , "filthy" ] ,
    comments : [ 
        { author :"will" , text : "i don't like the color" } , 
        { author :"jenny" , text : "can i get that in green?" } 
    ],
    other : { bar : 14 }
});

码头工人撰写

mongo:
    image: mongo
    container_name: mongo1
    environment:
      MONGO_INITDB_ROOT_USERNAME: test
      MONGO_INITDB_ROOT_PASSWORD: admin
      MONGO_INITDB_DATABASE: test
    volumes:    
      - ./init.js:/docker-entrypoint-initdb.d/init.js
    ports:
      - 27017:27017

推荐阅读