Mongo CLI
Basic Commands
The following quick commands can be executed in the MongoDB shell. To do this, you must connect to the server or container and call the CLI with the correct authorizations:
mongo
List Databases
show dbs;
Use Database
use <yourdatabasename>;
List Collections
show collections;
Use Collection
use <yourcollectionname>;
Show all Entries
use <yourdatabasename>;
db.<yourcollectionname>.find();
Delete Database
use <yourdatabasename>;
db.dropDatabase();
Delete Collection
use <yourdatabasename>;
db.<yourcollectionname>.drop();
Insert Data
use <yourdatabasename>;
db.<yourcollectionname>.insertOne({"id":"123456789","name":"test","email":"test@test","password":"p49QSIBnEtJA3lD8kH5NYe"})
Duplicate Database
use <yourdatabasename>;
db.<yourcollectionname1>.find().forEach(function(d){ db.getSiblingDB('<yourcollectionname2>')['<yourcollectionname1>'].insert(d); });
Backup & Restore Data
With these commands, entire database instances as well as individual collections can be backed up and restored correctly. There are several options for the level at which this can be done.
Backup
The following command backups the entire instance of MongoDB with all databases and collections including their contents.
mongodump --host="<yourmognodbinstance>:<yourmongodbport>" --port=<yourmongodbport> -o "<youroutputpatchforbackupfiles>"
If you only want to back up a single database, you can add the name to the path.
mongodump --host="<yourmognodbinstance>:<yourmongodbport>/<yourdatabasename>" --port=<yourmongodbport> -o "<youroutputpatchforbackupfiles>"
Restore
Import data to Collection
mongorestore -d <yourdatabasename> -c <yourcollectionname> <yourpathtosinglebsonfile>
Restore single Collection
mongorestore --drop -d <yourdatabasename> -c <yourcollectionname> "<yourpathtosinglebsonfile>"
Restore complete Database
mongorestore -d <yourdatabasename> "<yourpathtodatabasebackupfolder>"
// SAME FOR WINDOWS
.\mongorestore.exe --uri "mongodb://<yourmognodbinstance>:<yourmongodbport>" -d <yourdatabasename> "<yourpathtodatabasebackupfolder>"