MongoDB

Backups

Backup a specific mongodb. This is generally slower than physical backups but good for grabbing very specific subsets of data from big db *this version doesn’t include db users in the dump file

mongodump --archive=a.gz --gzip --db <dbname>

If you want users too, don’t specify the db (the admin db will be included in the dump and it has users)

mongodump --archive=a.gz --gzip

Restoring a dumpfile

mongorestore --archive=a.gz --gzip 

Commands

# list engine type (default should be WiredTiger since 3.2+)
db.serverStatus().storageEngine
db.serverStatus() # is kinda interesting in general

# a few basic commands that give me a sense of a mongod server
show dbs
use test
show collections
db.collection.find({})
db.collection.insertOne({
  "a": 1
})

CSV export of a collection, certain fields

# Mongoexport is great for this. It handles generating csv in the right format from documents
mongoexport --db <db> --collection <coll> --type=csv --fields "<field1>,<field2>,..." -u<user>

Connection strings

# DNS seed list (Mongodb > 3.6)
# We can setup a srv record that contains many or all hosts in a mongodb replica set
mongodb+srv://db.cluster.env/dbname
# This will pull a list of ips,ports from that srv record and connect to one host. After successfully connecting to the replicaset it will ask the rs for further hosts
# There are options that can be passed along with this (standard ones) and this mode can also lookup a corresponding TXT record to get the replicaset name + authdb

# Standard connection string
mongodb://[username:[email protected]]host1[:port1][,...hostN[:portN]][/[database][?options]]
# You can explicitly list all members of a replica set using this method
# I believe the driver only needs to find one replica set member and then can discover others and even follow mongo elections

Links

Schema design

Links