且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将json中的数据导入到mongo容器docker

更新时间:2022-11-03 09:42:10

您不能仅使用docker-compose导入JSON。您需要将数据放在js文件中,并使用 /docker-entrypoint-initdb.d js 文件挂载/ p>

You can not import JSON simply using docker-compose. you need to place the data in js file and mount the js file with /docker-entrypoint-initdb.d


首次启动容器时,它将执行扩展名为 .sh的文件

/docker-entrypoint-initdb.d 中找到的code>和 .js 。文件将按照字母
的顺序执行。 .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.

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

docker-compose

docker-compose

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