ChatGPT解决这个技术问题 Extra ChatGPT

How do I drop a MongoDB database from the command line?

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

see this question: stackoverflow.com/questions/3366397/…. It's really easy to do it from the mongo shell.

T
Tim Gautier

Like this:

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

More info on scripting the shell from the command line here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting


This was very helpful in my case. Somehow I had a database named "mean-dev" from an older installation, and entering "mean-dev.dropDatabase()" in the mongo shell resulted in "ReferenceError: mean is not defined". But using the solution in this answer did the trick. +1
If you want to get a human readable result, do it this way: mongo <dbname> --eval "printjson(db.dropDatabase())"
K. P. MacGregor. you should have been: "use mean-dev" + "db.dropDatabase()"
Thanks. This is how you can customise host and port: mongo <yourDb> --host <yourHost> --port <yourPort> --eval 'db.dropDatabase()'
D
Dan Dascalescu

The best way to do it is from the mongodb console:

> use mydb; 
> db.dropDatabase();

Alternatively, you can stop mongod and delete the data files from your data directory, then restart.

Hint: you can also move the data files to a subfolder, and delete them if you're sure you no longer need them.


I think he means directly from the prompt doesn't he? In that case you either have to generate a .js file with those commands and invoke it from the prompt using "mongo dropdb.js" or something or do as you say and remove the files manually.
but be aware that you cannot use use command in .js file, you have to connect to concrete DB (specify dbname for mongo command)
Pro Tip: after dropping a database, you might want to exit the mongo shell and delete your ~/.dbshell file to clear your command history. (There may be a better way of doing that - I'm not sure.) I do this because, unlike with SQL, the mongo command to drop a database does not actually reference the name of the database to drop - it just drops the database to which the client is currently connected. Clearing your command history will prevent your from accidentally replaying the dropDatabase command and unintentionally dropping a second database.
That's a smart idea, @chrisallenlane. The mongodb shell is quite a dangerous tool at times... :)
Warning: If you drop a database and create a new database with the same name, you must either restart all mongos instances, or use the flushRouterConfig command on all mongos instances before reading or writing to that database. This action ensures that the mongos instances refresh their metadata cache, including the location of the primary shard for the new database. Otherwise, the mongos may miss data on reads and may write data to a wrong shard.
A
Alex Baban

I found this easy to remember:

mongo //to start the mongodb shell

show dbs //to list existing databases

use <dbname> //the <dbname> is the database you'd like to drop

db //should show <dbname> just to be sure I'm working with the right database

db.dropDatabase() //will delete the database & return { "dropped" : "<dbname>", "ok" : 1 }

m
mikemaccana

You don't need heredocs or eval, mongo itself can act as an interpreter.

#!/usr/bin/env mongo
var db = new Mongo().getDB("someDatabase");
db.dropDatabase();

Make the file executable and run it.


Note that the script name must end with .js, otherwise it will be interpreted as the db address.
@Vegard That's not correct. You're running mongo filename which is unnecessary - the file already has an interpreter in the top line. Just make the file executable and run it ./filename
@mikemaccana I know that, but doing ./filename will actually run /usr/bin/env mongo filename, right? And so if filename doesn't end in .py, mongo will not recognise the argument as a script to run.
"Doing ./filename will actually run /usr/bin/env mongo filename, right?" No. Check the output of ps.
@mikemaccana The output of ps only shows you what's running at the time you invoke ps, not the chain of exec calls that lead to that point nor the work the kernel has done to load and execute the file. If you want to know what's really going on, you should use write a wrapper around /usr/bin/env, set that as the executable in the shebang line, and then kick the whole thing off with strace.
b
bud-e

Start MongoDB

Command for Database drop is :

1. first select the database which you want to delete

use < database name >

2. Then use this..

db.dropDatabase()

D
David

You could also use a "heredoc":

mongo localhost/db <<EOF
db.dropDatabase()
EOF

Results in output like:

mongo localhost/db <<EOF
db.dropDatabase()
EOF
MongoDB shell version: 2.2.2
connecting to: localhost/db
{ "dropped" : "db", "ok" : 1 }    
bye

I like to use heredocs for things like this, in case you want more complex sequence of commands.


b
bhv

Here are some use full delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

directly from command prompt or blash : mongo mydb --eval "db.dropDatabase()


G
Gabriel Mancini

Other way:

echo "db.dropDatabase()" | mongo <database name>

D
Diosney

Execute in a terminal:

mongo // To go to shell

show databases // To show all existing databases.

use <DATA_BASE> // To switch to the wanted database.

db.dropDatabase() // To remove the current database.

Same answer as this one, which was given a month earlier.
h
helcode

Open another terminal window and execute the following commands,

mongodb
use mydb
db.dropDatabase()

Output of that operation shall look like the following

MAC:FOLDER USER$ mongodb
> show databases
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
> use mydb
switched to db mydb
>db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
>

Please note that mydb is still in use, hence inserting any input at that time will initialize the database again.


M
Matt Ke

Open a terminal and type:

mongo 

The below command should show the listed databases:

show dbs 

/* the <dbname> is the database you'd like to drop */
use <dbname> 

/* the below command will delete the database */
db.dropDatabase()  

The below should be the output in the terminal:

{
  "dropped": "<dbname>",
  "ok": 1
}

s
sergiuz

Using Javascript, you can easily create a drop_bad.js script to drop your database:

create drop_bad.js:

use bad;
db.dropDatabase();

Than run 1 command in terminal to exectue the script using mongo shell:

mongo < drop_bad.js

L
Lakmal Vithanage

Eventhough there are several methods, The best way (most efficient and easiest) is using db.dropDatabase()


Q
Quentin

In you command prompt, First connect to mongodb using following command:

mongo -h [host-name]:[port:number] -d [dbname] -u [username] -p [password]

you will be accessing db with <dbname>.

Run the following command to drop the whole database:

db.dropDatabase()

-h is help, -d is not an option more like ` mongo --host [host-name]:[port:number] -u [username] -p [password] [dbname] --eval "db.dropDatabase()" `
v
valdeci

one liner remote remove all collections from mongo database

note must use --host, (-h is help for mongo command), and -d is not an option, select the db and command after password.

mongo --host <mongo_host>:<mongo_port> -u <db_user> -p <db_pass> <your_db> --eval "db.dropDatabase()"

B
Buzz Moschetti

Surprised that we haven't seen this variation come up. This minimizes extra args on the command line and explicitly shows the DB being switched to FOO and then dropped:

$ mongo --host "mongodb://machine:port" --eval 'db.getSiblingDB("FOO").dropDatabase();'


S
Shrinivas Kalangutkar

LogIn into your mongoDB command line: And type the below commands. use "YOUR_DATABASE_NAME"; db.dropDatabase();


J
Joe Drumgoole

Drop a MongoDB database using python:

import argparse

import pymongo


if __name__ == "__main__":
    """
    Drop a Database.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default='mongodb://localhost:27017',
                        help="mongodb URI [default: %(default)s]")
    parser.add_argument("--database", default=None,
                        help="database name: %(default)s]")

    args = parser.parse_args()

    client = pymongo.MongoClient(host=args.host)

    if args.database in client.list_database_names():
        client.drop_database(args.database)
        print(f"Dropped: '{args.database}'")
    else:
        print(f"Database '{args.database}' does not exist")

W
Wernfried Domscheit

In order to be really sure that you drop the correct database use

mongo <connection properties> --eval "db.getSiblingDB('dbname').dropDatabase()" 

See Authentication failure while trying to save to mongodb to understand the concerns.


S
Susil Kumar Behera

You can first switch to your database which you want to delete. Then you can delete the same by using the command dropDatabase().

Code :

>use dbName

>db.dropdataBase()

The result will be :

{ "dropped" : "dbName", "ok" : 1 }

If you want to delete a specific collection in a database, then switch to the database and enter the following command.

Code:

>use dbName

db.collection.drop()

The result will be :

true

If you want a better understanding of MongoDB shell commands it's better to follow the documentation always. Link to the documentation : https://www.mongodb.com/docs/manual/reference/method/#std-label-js-administrative-methods


n
nixxo_raa

db will show the current Database name type: db.dropDatabase();

1- select the database to drop by using 'use' keyword.

2- then type db.dropDatabase();


P
Pang

use following command from mongo shell to drop db

use <database name>; 
db.dropDatabase();

how does this command specify which database to drop? With a database called "auth-users" I tried > use auth-users ; db.dropDatabase() and > use auth-users; db.dropDatabase() and both returned [thread1] Error: [auth-users ; db.dropD atabase()] is not a valid database name :