Home > Net >  Get database name mongoDB with bash script
Get database name mongoDB with bash script

Time:07-14

I want to automate my mongo backup process with bash. My plan is to get all database name on mongo and store to a file, lets called "database-name.txt". Then I want to dump the database with for loop from that file and save the backup to other directory.

the problem:

  • everytime I connect mongo shell, it would show information like this
MongoDB shell version v5.0.9
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("some-random-string") }
MongoDB server version: 5.0.9
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
admin      0.000GB
config     0.000GB
local      0.000GB
database1  0.000GB
database2  0.000GB
bye

I dont need this information and just want to save my database name. I've search for all possibility but still not get it done. How I supposed to do it?

CodePudding user response:

Try mongo --quiet

However, it still prints the deprecation warning. You get rid of it in combination with --eval but then command show dbs is not possible

mongo --quiet --eval 'show dbs'

uncaught exception: SyntaxError: unexpected token: identifier :
@(shell eval):1:5
exiting with code -4

So, final solution is Mongo.getDBNames() or listDatabases

mongo --quiet --eval "db.adminCommand( { listDatabases: 1 } ).databases.map(x => x.name).join('\n')" > database-name.txt

mongo --quiet --eval "db.getMongo().getDBNames().join('\n')" > database-name.txt

should return file of

admin 
config 
local 
database1 
database2
  • Related