Link

Mongo DB

Mongo DB is used to store JSON documents. It is the backend storage for the Unifi Network Controller.

Table of contents

  1. Init with authentication
  2. Backup Mongo DB
  3. Restore Mongo DB

Init with authentication

Initialization of a new Mongo DB instance via the official Docker container is not trivial.

First set the required environment variables then add a script to /docker-entrypoint-initdb.d/.

The below script initializes Mongo DB for thr UniFi Controller:

#!/bin/bash

MONGO_DB_USER="$(< ${MONGO_DB_USER_FILE})"
MONGO_DB_PASS="$(< ${MONGO_DB_PASS_FILE})"

create_user() {
    mongo admin \
        --host localhost \
        --eval "db.createUser($1);"
}

create_user "{
    user: '${MONGO_DB_USER}',
    pwd:  '${MONGO_DB_PASS}',
    roles: [
        {
            role: 'readWrite',
            db:   '${MONGO_INITDB_DATABASE}'
        },
        {
            role: 'readWrite',
            db:   '${MONGO_INITDB_DATABASE}_stat'
        }
    ]
}"

Backup Mongo DB

Mongo DB puts a lot of warnings in the documentation about using mongodump to create a backup. This warning is aimed at huge corporate databases. However the database for the UniFi controller is small so the mongodump tool is safe to use.

mongodump \
    --host=unifi/mongodb-0.mongodb:27017,mongodb-1.mongodb:27017,mongodb-2.mongodb:27017 \
    --username=${MONGO_DB_USER} \
    --password=${MONGO_DB_PASS}
tar zcvf mongodb-backup.tar.gz /dump/

Restore Mongo DB

It is not clear at all from the Mongo DB documentation, but it is no problem to restore a DB dump to a ReplicaSet. The only condition is that the full ReplicaSet must be available to the host where the restore takes place.

tar zxvf mongodb-backup.tar.gz
mongorestore \
    --host=unifi/mongodb-0.mongodb:27017,mongodb-1.mongodb:27017,mongodb-2.mongodb:27017 \
    --username=${MONGO_DB_USER} \
    --password=${MONGO_DB_PASS}