1

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 Answers 5

7

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();"
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, '&&' will executing the command on the right only if the command on the left succeed.
3

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
$

Comments

1

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

Comments

1

Just try this command on terminal.

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

Comments

1

You can use echo too:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.