MongoDBΒΆ

Replication:

# run minimum 3 mongo nodes
# execute next command on the one node
rs.initiate({_id: "rs1", members: [{_id: 0, host: "mongo1:27017" }, {_id: 1, host: "mongo2:27017"}, {_id: 2, host: "mongo3:27017"}]});
# or
mongo --quiet --eval "rs.initiate({_id: 'rs1', members: [{_id: 0, host: 'mongo1:27017' }, {_id: 1, host: 'mongo2:27017'}, {_id: 2, host: 'mongo3:27017'}]});"

# check conf
rs.conf()

# check status
rs.status()

# allow queries from secondary (applied for current session)
rs.slaveOk()

Insert values:

db.<collection>.insertMany([
   { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] }
]);

Execute JS code:

mongo [db_name] --quiet --eval "<JS_code>"

Print a list of all databases on the server:

show dbs
# or
db.getMongo().getDBNames()
# or
printjson(db.adminCommand('listDatabases'))

Switch current database to <db>. The mongo shell variable db is set to the current database:

use <db>    # The command will create a new database if it doesn't exist

Backup/restore MongoDB data:

mongodump --host=mongodb:27017 --db <dbname> --archive | mongorestore --host=rs1/mongo1:27017,mongo2:27017,mongo3:27017 --archive

# docker

# dump
docker exec <container> sh -c 'mongodump --archive' > mongodb.dump

# restore
docker exec -i <container> sh -c 'mongorestore --archive' < mongodb.dump

Print a list of all collections for current database:

show collections
# or
db.getCollectionNames()
# or
show tables

Print documents of collection:

db.<collection>.find().pretty()

Get all documents of all collections of current DB:

var c = db.getCollectionNames(); for (var i = 0; i < c.length; i++) { print('[' + c[i] + ']'); db.getCollection(c[i]).find().forEach(printjson); }

Get DBs, collections and docs count:

db.getMongo().getDBNames().forEach((d) => {
  print('[' + d + ']');
  db = db.getSiblingDB(d);
  db.getCollectionNames().forEach((c) => {
    print('\t' + c + ': ' + db.getCollection(c).count());
  });
});

# single line
db.getMongo().getDBNames().forEach((d)=>{print('['+d+']');db=db.getSiblingDB(d);db.getCollectionNames().forEach((c)=>{print('\t'+c+': '+db.getCollection(c).count())})})