MongoDB Collection/Tabelle exportieren und in MariaDB importieren

MongoDB Collection/Tabelle exportieren und in MariaDB importieren

In diesem Beispiel zeige ich in aller Kürze, wie alle MongoDB-Tabellen als JSON exportiert werden können. Anschließend wird gezielt eine .json-Datei (als Tabelle) ausgewählt und in das CSV-Format übertragen, damit die CSV-Datei später komfortabel über phpMyAdmin in MariaDB importiert werden kann. Das Skript in diesem Beispiel kann natürlich direkt auf dem Hostsystem verwendet werden, auch wenn MongoDB in einem Docker Container ausgeführt wird.

Tools installieren:

sudo apt install -y mongodb-database-tools
sudo apt-get install jq

Alle Tabellen der Datenbank admin per export.sh exportieren:

#!/bin/bash

DB="admin"
AUTH="mongodb://user:pass@localhost:27017/$DB"
EXPORT_DIR="/root/mongo_exports"

mkdir -p "$EXPORT_DIR"

collections=$(mongosh "$AUTH" --quiet --eval "db.getCollectionNames().join(' ')" )

for col in $collections; do
    echo "Exporting $col..."
    mongoexport --uri="$AUTH" --collection="$col" --out="$EXPORT_DIR/${col}.json" --jsonArray
done

ggf. kopieren:

mv /root/mongo_exports/ /var/www/vhosts/example.com/
cd /var/www/vhosts/example.com/

json in csv umwandeln:

jq -r '(.[0] | keys_unsorted) as $cols | $cols, map([.[ $cols[] ]])[] | @csv' table.json > table.csv

Falls es verschachtelte Objekte gibt wird ein Fehler wie „jq: error (at table.json:1): object ({„$oid“:“68…) is not valid in a csv row“ auftauchen – Lösung:

jq -r '
  (.[0] | keys_unsorted) as $cols |
  $cols,
  map(
    [ $cols[] as $c |
      if (.[ $c ] | type) == "object" then
        (.[ $c ] | tojson)
      else
        .[ $c ]
      end
    ]
  )[] | @csv
' table.json > table.csv

Kopfzeile anschauen und entsprechende CREATE-Anweisungen erstellen, also z. B:

CREATE TABLE EXAMPLETABLE (
  _id VARCHAR(255) PRIMARY KEY,
  userId VARCHAR(255),
  name VARCHAR(255),
  email VARCHAR(255),
  phone VARCHAR(50),
  createdAt DATETIME
);

und in phpmyadmin als SQL ausführen. Dann die Tabelle phpmyadmin auswählen und die csv-Datei importieren. Fertig 🙂

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert