Como restaurar BD de MongoDB

Como restaurar BD de Mongo 

La base de datos TEST es donde se quiere restaurar los archivos que tenemos del backup. 

mongorestore --host=localhost --port=27021 --authenticationDatabase="admin" -u="dba" -p="*****" --db test  /backup_mongodb/test/ 





Este es el mensaje que genera el log del restore



Crear Backup de BDs de MongoDB

Crear Backup de BDs de MongoDB

mongodump --host=localhost --port=27021 --authenticationDatabase="admin" -u="dba" -p="****" --out=/backup_mongodb




Sino se tiene autenticación habilitada

mongodump --host=localhost --port=27021 --out=/backup_mongodb




MongoDB en replicaset para pruebas

Mongo con Replicaset en 1 solo Nodo

con usuario mongod vamos a editar el archivo de configuración que trae la instalación.
vi /etc/mongod.conf

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /mongo_data/single/
  journal:
    enabled: true
  directoryPerDB: true
  wiredTiger:
    engineConfig:
       cacheSizeGB: 1
       journalCompressor: snappy
       directoryForIndexes: true

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27024
  bindIp: 0.0.0.0

#security:
#  authorization: enabled #Se modifica al final cuando se haya creado el usuario de autenticacion

#operationProfiling:

replication:
  #oplogSizeMB: 1024
  replSetName: mongodbsingle
#sharding:

[root@vm-l-01 etc]# ls -larth mongo*
-rw-r--r-- 1 mongod mongod 711 Jul 14 19:52 mongod.conf


Iniciar servicio
[root@vm-l-01 etc]# systemctl start  mongod
[root@vm-l-01 etc]# systemctl status  mongod


[root@vm-l-01 etc]# systemctl stop  mongod

--con usuario mongod
[mongod@vm-l-01 ~]$ mongo --host localhost:27024
MongoDB shell version v4.2.14-rc0

--Creamos el Nodo que va a utilizar la replication
> rs.initiate({_id : "mongodbsingle",members: [{ _id : 0, host : "192.168.9.204:27024" }]})
{ "ok" : 1 }

--Revisamos el estado de los nodos de la replica
mongodbsingle:PRIMARY> rs.status()


{
    "set" : "mongodbsingle",
    "date" : ISODate("2021-07-14T19:49:23.275Z"),
    "myState" : 1,
    "term" : NumberLong(1),
    "syncingTo" : "",
    "syncSourceHost" : "",
    "syncSourceId" : -1,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "majorityVoteCount" : 1,
    "writeMajorityCount" : 1,
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(1626292154, 1),
            "t" : NumberLong(1)
        },
        "lastCommittedWallTime" : ISODate("2021-07-14T19:49:14.037Z"),
        "readConcernMajorityOpTime" : {
            "ts" : Timestamp(1626292154, 1),
            "t" : NumberLong(1)
        },
        "readConcernMajorityWallTime" : ISODate("2021-07-14T19:49:14.037Z"),
        "appliedOpTime" : {
            "ts" : Timestamp(1626292154, 1),
            "t" : NumberLong(1)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1626292154, 1),
            "t" : NumberLong(1)
        },
        "lastAppliedWallTime" : ISODate("2021-07-14T19:49:14.037Z"),
        "lastDurableWallTime" : ISODate("2021-07-14T19:49:14.037Z")
    },
    "lastStableRecoveryTimestamp" : Timestamp(1626292114, 4),
    "lastStableCheckpointTimestamp" : Timestamp(1626292114, 4),
    "electionCandidateMetrics" : {
        "lastElectionReason" : "electionTimeout",
        "lastElectionDate" : ISODate("2021-07-14T19:48:34.026Z"),
        "electionTerm" : NumberLong(1),
        "lastCommittedOpTimeAtElection" : {
            "ts" : Timestamp(0, 0),
            "t" : NumberLong(-1)
        },
        "lastSeenOpTimeAtElection" : {
            "ts" : Timestamp(1626292114, 1),
            "t" : NumberLong(-1)
        },
        "numVotesNeeded" : 1,
        "priorityAtElection" : 1,
        "electionTimeoutMillis" : NumberLong(10000),
        "newTermStartDate" : ISODate("2021-07-14T19:48:34.036Z"),
        "wMajorityWriteAvailabilityDate" : ISODate("2021-07-14T19:48:34.042Z")
    },
    "members" : [
        {
            "_id" : 0,
            "name" : "192.168.9.204:27024",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 543,
            "optime" : {
                "ts" : Timestamp(1626292154, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2021-07-14T19:49:14Z"),
            "syncingTo" : "",
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "could not find member to sync from",
            "electionTime" : Timestamp(1626292114, 2),
            "electionDate" : ISODate("2021-07-14T19:48:34Z"),
            "configVersion" : 1,
            "self" : true,
            "lastHeartbeatMessage" : ""
        }
    ],
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1626292154, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1626292154, 1)
}

--Listar las BD de Inicio
mongodbsingle:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB











--Pasamos a admin
mongodbsingle:PRIMARY> use admin
switched to db admin

--Creamos el usuario
mongodbsingle:PRIMARY> db.createUser( { user: "dba", pwd: "dba2021*", roles: [ { role:"root", db:"admin" } ] } )
Successfully added user: {
    "user" : "dba",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
mongodbsingle:PRIMARY> show users
{
    "_id" : "admin.dba",
    "userId" : UUID("a35e5a67-06d3-4a63-a4a4-9f3408841f95"),
    "user" : "dba",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}
mongodbsingle:PRIMARY> exit
bye

--Habilitar la autenticacion
[root@vm-l-01 /]# systemctl stop  mongod
[root@vm-l-01 /]# vi /etc/mongod.conf
--descomentar las lineas
security:
  authorization: enabled

--Volver a subir servicio de MongoDB
[root@vm-l-01 /]# systemctl start mongod
[root@vm-l-01 /]# systemctl status mongod

[mongod@vm-l-01 ~]$ mongo -u dba --host localhost:27024
pwd:*****

---Ver el alert de la BD
[mongod@vm-l-01 mongodb]$ tail -300f /var/log/mongodb/mongod.log








---Probar conexión por herramienta MongoDB Compass