I'm not a Bash/Linux person, but I've been asked to just come up with the lines needed to run to authenticate against a database and then drop it. Here is what I have so far and I'm not sure if it's correct:
mongo mydatabase –port –username <username> –password <password> –authenticationDatabase admin –eval “ printjson(db.dropDatabase())”
If it's possible to use one line to delete any database whose name starts with "cpt_" then that would be absolutely ideal.
Thanks!
You can use -
Get all the names
Loop and check if the name starts with cpt_
drop the database
db.getMongo().getDBNames().forEach(function(dbName){ if (dbName.startsWith('cpt_')) printjson(db.getSiblingDB(dbName).dropDatabase())
Full
mongo –port –username <username> –password <password> –authenticationDatabase admin --eval "db.getMongo().getDBNames().forEach(function(dbName){ if (dbName.startsWith('cpt_')) printjson(db.getSiblingDB(dbName).dropDatabase()) })"
Related
So I have a MongoDB in an Azure Cosmos DB service. It contains a collection of 1500 documents and I want to download this whole collection in a JSON format. I've tried several methods without success, namely
test_collection.find({})
Which gave me a cursor timeout. Using
{ timeout : false }
Did not help. Then I tried to use mongoexport:
mongoexport -h host_name --port 1234 -u user_name -p password
-d admin -c collection_name -o data.json --ssl
which gives me 0 exported records. The firewall IP access control is off and I can connect to the database through Mongo shell just fine. Trying to export other collections doesn't work either. Also, it has to be by ssl otherwise I get a "database not found" right away.
I've thought about using skip and limit but it doesn't seem to be a good idea with large (and expanding) collections? Could someone please give me some advise as to how I best achieve or overcome these obstacles to download my collection? It doesn't matter how, I just simply need to download the collection. Thank you.
You possibly have a few incorrect parameters, and a missing parameter:
Are you sure your database name is admin?
You need to specify --sslAllowInvalidCertificates
For host/port: this should look something like:
/h yourcosmosaccount.documents.azure.com:10255
If you take a look at the "quick start" tab in your Cosmos DB settings, you'll see the command line string for mongo (well, mongo.exe in the example). Just grab those parameters and use them for mongoexport.
I just ran this against a sample Cosmos DB (MongoDB API) database of mine, with no issue:
Here's the generic command-line equivalent:
mongoexport /h <host:port> /u <username> /p <password> /ssl /sslAllowInvalidCertificates /d <database> /c <collection> /o <outputfile>.json
I have credentials for root user and I am using those credentials to automate db backup. Main aim is to create prototype for Automated DB backup and, for simplicity, I am using root. The script (I borrowed from article) looks like as follows:
#!/bin/bash
#Force file syncronization and lock writes
mongo admin -u "root" -p "root" --eval "printjson(db.fsyncLock())"
MONGODUMP_PATH="/usr/bin/mongodump"
MONGO_DATABASE="mydb" #replace with your database name
TIMESTAMP=`date +%F-%H%M`
S3_BUCKET_NAME="mydb" #replace with your bucket name on Amazon S3
S3_BUCKET_PATH="backup/mongo"
# Create backup
$MONGODUMP_PATH -d $MONGO_DATABASE
# Add timestamp to backup
mv dump mongodb-$HOSTNAME-$TIMESTAMP
tar cf mongodb-$HOSTNAME-$TIMESTAMP.tar mongodb-$HOSTNAME-$TIMESTAMP
# Upload to S3
s3cmd put mongodb-$HOSTNAME-$TIMESTAMP.tar s3://$S3_BUCKET_NAME/$S3_BUCKET_PATH/mongodb-$HOSTNAME-$TIMESTAMP.tar
#Unlock database writes
mongo admin -u "root" -p "root" --eval "printjson(db.fsyncUnlock())"
#Delete local files
#rm -rf mongodb-*
I am getting following error:
Failed: error getting collections for database mydb: error running
listCollections. Database: mydb Err: not authorized on mydb to
execute command { listCollections: 1, cursor: {} }
Isnt root has all the access over all the databases? I am bit scared that I might run into situation where I am thinking to supersede something with root but It doesnt have the permission. This is the root cause of posting question. I want to avoid surprises like this in the future.
The error mentioned above was misleading for me. But my script was wrong or incomplete.
If you look at following line in my script:
$MONGODUMP_PATH -d $MONGO_DATABASE
I am not providing any user in Mongodump command and hence the error message. If I rewrite that line something as follows:
$MONGODUMP_PATH -d $MONGO_DATABASE --authenticationDatabase "admin" -u "dbowner" -p "pwd"
then error goes away.
I am attempting to create a single archive file for each database in Mongo. Is there a way to create a batch file that will automatically create an archive (.archive) for each database without me manually entering the database name?
The snipet provided
mongodump --host hostename --port portname --username username --password password --authenticationDatabase admin --db databasename --archive=name.arvhive
I would like to create the archive file without having to specify the database name. Is this possible? If not, is there a way to dump all of the databases and create a single gzip for each database?
Any assistance would be greatly appreciated.
Thanks!
In order to get the DB names in the mongo instance we need to use the mongo show dbs command.
Since we want to be able to use this inside a script, we want to run that command and exit the mongo cli, to do that we can pass a js file to mongo, like so:
$ echo "show dbs" > showDbs.js
$ mongo < showDbs.js
Which will result in something like
MongoDB shell version v3.4.22
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.22
admin 0.000GB
animals 0.366GB
people 0.012GB
local 0.000GB
bye
Since we need to parse the result, we can use the --quiet option to reduce the output. We can also skip creating the showDbs.js file so that we don't have to clean it up later.
Now we have:
$ mongo --quiet <<< "show dbs"
admin 0.000GB
animals 0.366GB
people 0.012GB
local 0.000GB
All that's left to do is to parse the result to remove the db sizes, and then run the mongodump command for each of the databases (I'm leaving that command as it is)
To remove the size information for each database we'll use sed and match for a whitespace, since whitespaces are not allowed in database names
$ sed 's/\s\+.\+//' <<< "$dbs"
Putting it all together we get the following script
#!/bin/bash
dbs=$(mongo --quiet <<< "show dbs")
dbs=$(sed 's/\s\+.\+//' <<< "$dbs")
for db in $dbs; do
mongodump --host hostname --port portname --username username --password password --authenticationDatabase admin --db $db --archive=$db.archive
done
I have set up a MongoDB database with an admin user that has only administrative rights, not read or write access to databases.
What I now would want to do is:
Add a new database,
and add a new user to that database.
And: I need to do this from the command line. So I tried:
$ mongo admin -u admin -p admin --eval "db.addUser('dummyuser', 'dummysecret')"
(Please note that as I am still running MongoDB 2.0, I am using the old format of db.addUser.)
This would make perfect sense if I could also tell it which database this user should be for. But now I am struggling. How do I specify the database for this command? If I were in the interactive shell, I could just run
> use dummydb
but how do I do this from the command line? My first try was to concatenate both commands with a ;, but this didn't work:
$ mongo admin -u admin -p admin --eval "use dummydb;db.addUser('dummyuser', 'dummysecret')"
just gives me syntax error.
How do I get this right?
The use db syntax is only supported in an interactive shell session.
If you want to change databases from an admin script, you can use db.getSiblingDB('dbname').
So your equivalent command line using --eval would be:
# MongoDB 2.6+: use createUser()
$ mongo admin -u admin -p admin --eval "db.getSiblingDB('dummydb').createUser({user: 'dummyuser', pwd: 'dummysecret', roles: ['readWrite']})"
# MongoDB 2.4: use addUser()
$ mongo admin -u admin -p admin --eval "db.getSiblingDB('dummydb').addUser('dummyuser', 'dummysecret')"
There is a section in the MongoDB manual covering Differences between interactive and scripted mongo. This includes equivalents for other interactive shell helpers such as show dbs and show collections.
Solved it by putting the commands
use dummydb
db.addUser('dummyuser', 'dummysecret')
into a .js file, and then ran MongoDB by calling:
$ mongo admin -u admin -p admin < setupMongoDB.js
That's it :-)
Above in my case didn't worked
use dummyDb
db.createUser({user: "admin",pwd: "secrectP#wd",roles: [ { role: "readWrite", db: "reporting" } ],mechanisms: [ "SCRAM-SHA-256" ] }
We are using MongoDB user based authentication, and I want to quickly run a command to check whether a user has already been created in the database, in order that puppet won't repeatedly attempt to create the user.
Here is how we check if the replica set has initialised:
/usr/bin/mongo --host ${members[0]} --quiet --eval 'rs.status().ok' | grep -q 1
Is a similar trick possible with authentication? I've checked the documentation here http://www.mongodb.org/display/DOCS/dbshell+%28mongo%29+Reference and I can't see a way of doing it?
Yes, on a given DB, you can use db.system.users.find({user:'login'}).count() which will return 0 if the user does not exist.
It feels that this method has been deprecated, I needed the following command to work:
db.getUsers({filter: {'user': 'login'}})
Today I just tried -u and -p options for mongo command and it worked for me:
mongo --port 27037 --quiet -u superuser -p pwd
--eval "db.system.users.find({user:'user3'}).count()" admin
Note the last "admin" arg - it is the name of database, to which you are authenticating.
To check if a user username exists:
db.runCommand({ usersInfo: { user: "username", db: "admin" } }).users.length == 1
This will return true if the user exists, and false otherwise. (If the user was created in another database, replace admin with the name of the database.)
You can also use findOne
db.system.users.findOne({user:'login'})
it will null if no user
it will return user if found