Skip to content

Initializing MongoDB with JSON Data

Posted on:January 29, 2024 at 08:00 AM

Initializing MongoDB with JSON Data

This tutorial will guide you through the process of seeding MongoDB with ship data. Seeding the database is crucial for populating it with initial data, ensuring your application has a starting dataset.

Seed MongoDB Final Result

Prerequisites

Before you begin, make sure you have the following prerequisites installed on your system:

Setting Up MongoDB Container

Firstly, define your MongoDB container in a Docker Compose file (docker-compose.yml). This configuration includes the necessary settings, such as username, password, and port:

version: '3'
services:
  mongodb:
    container_name: mongodb
    build:
      context: ./mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - '27017:27017'
    volumes:
      - mongodb_data:/data/db
    healthcheck:
      test: |
        test $$(mongosh --quiet -u root -p root --eval "try { rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: 'mongodb' }] }).ok } catch (_) { rs.status().ok }") -eq 1
      interval: 10s
      start_period: 30s

  mongodb-seed:
    image: mongo:7.0
    links:
      - mongodb
    volumes:
      - ./mongodb-seed:/mongodb-seed
    command:
      /mongodb-seed/import.sh

Seeding MongoDB with Ship Data

Now, let’s create the import.sh script in the mongodb-seed directory. This script uses mongoimport to add ship data to the MongoDB database:

#!/bin/bash

mongoimport --username root --password root --host mongodb --port 27017 --db geoglify --mode upsert --collection ships --authenticationDatabase=admin --type json --file /mongodb-seed/ships.json --jsonArray

The ships.json file contains sample ship data in JSON format.

[
  {
    "breadth": "",
    "country_name": "Panama",
    "country_code": "PA",
    "call_sign": "3FEI5",
    "cargo": "Cargo",
    "draught": 7,
    "imo": 9660607,
    "length": "",
    "name": "MEDI MANILA",
    "mmsi": 353664000
  },
  {
    "breadth": 11,
    "country_name": "Netherlands",
    "country_code": "NL",
    "call_sign": "PBTJ",
    "cargo": "Cargo",
    "draught": 3.299999952316284,
    "imo": 9559614,
    "length": 99,
    "name": "EEMS SOLAR",
    "mmsi": 246367000
  }
]

Running the Seed Process

To seed MongoDB with ship data, follow these steps:

  1. Open a terminal and navigate to the directory containing your docker-compose.yml file.

  2. Run the following command to start the MongoDB containers:

docker-compose up -d
  1. After the containers are running, execute the import.sh script to seed the database:
docker-compose exec mongodb-seed /mongodb-seed/import.sh

Now, your MongoDB database should be populated with ship data. Feel free to adapt this tutorial to your specific needs and datasets. Happy coding!