0
votes

What's the easiest way to do this from my bash prompt?

I know that I can drop a database using below:

mongo <dbname> --eval "db.dropDatabase()"

I want to do the same for a collection preferably in a shell script or python script and not from mongodb console.

What I am trying to achieve is first take a mongodump of the collection and then drop the collection:

Command I am using for dump:

mongodump --db database --collection collection_03-11-2016 --out /home/mongodump
5

5 Answers

6
votes

If you want to do this in bash one liner. The easiest would be -

mongodump --db yourdatabase --collection yourcollection --out /home/mongodump && mongo --eval "db=db.getSiblingDB('yourdatabase'); db.yourcollection.drop();"
3
votes

You can write a javascript file with multiple commands in it and give that to the mongo command for execution.

Let's say, you create a js file called delete_collection.js as follows:

use foo        //DB name - foo
db.bar.drop()  //Collection drop (collection name - bar)

Then, you can run the following command from bash/terminal to execute it.

$ mongo < delete_collection.js
Mongo shell version: 3.0.4
Connecting to: test
switched to db foo
true
bye
$
1
votes

To answer my own question, I had mongo collections according to dates in a db and wanted a shell script to backup and delete collection older than 10 days.

Using Abhay PS's script, I wrote the following .sh script:

#!/bin/bash

MONGO_DATABASE="db_name"
APP_NAME="collection_name_"

MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
TIMESTAMP=`date +%F -d "10 days ago"`
MONGODUMP_PATH="/usr/bin/mongodump"
BACKUPS_DIR="/home/user/mongodump/$TIMESTAMP"
BACKUP_NAME="$APP_NAME$TIMESTAMP"
MONGO_PATH="/usr/bin/mongo"

$MONGODUMP_PATH -d $MONGO_DATABASE -c $BACKUP_NAME

mkdir -p $BACKUPS_DIR
mv dump $BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUP_NAME
rm -rf $BACKUP_NAME

$MONGO_PATH --eval "db=db.getSiblingDB('${MONGO_DATABASE}'); db['${BACKUP_NAME}'].drop();"

One can also pass the path and zip parameters in the mongodump option using -o

1
votes

Just try this command on terminal.

mongodump --db <dbname> --collection <collection> && mongo <dbname> --eval 'db.<collection>.drop()'
1
votes

You can use echo too:

echo "db.collection.drop()" | mongo <dbname>