像这样:
mongo <dbname> --eval "db.dropDatabase()"
有关从命令行编写 Shell 脚本的更多信息,请参见: https : //docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting
最好的方法是从 mongodb 控制台执行:
> use mydb;
> db.dropDatabase();
或者,您可以停止mongod
并从数据目录中删除数据文件,然后重新启动。
提示:您也可以将数据文件移动到子文件夹中,如果确定不再需要它们,可以将其删除。
我发现这很容易记住:
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 }
您不需要 heredocs 或 eval , mongo
本身可以充当解释器。
#!/usr/bin/env mongo
var db = new Mongo().getDB("someDatabase");
db.dropDatabase();
使文件可执行并运行。
启动 MongoDB
用于数据库删除的命令是:
1.首先选择要删除的数据库
use < database name >
2.然后使用它。
db.dropDatabase()
您还可以使用 “heredoc”:
mongo localhost/db <<EOF
db.dropDatabase()
EOF
结果输出如下:
mongo localhost/db <<EOF
db.dropDatabase()
EOF
MongoDB shell version: 2.2.2
connecting to: localhost/db
{ "dropped" : "db", "ok" : 1 }
bye
如果您想要更复杂的命令序列,我喜欢将 heredocs 用于此类事情。
另一种方式:
echo "db.dropDatabase()" | mongo <database name>
这是一些使用 mongo shell 对 mongodb 使用完全删除操作的方法
要删除集合中的特定文档 : db.mycollection.remove( {name:"stack"} )
删除集合中的所有文档 : db.mycollection.remove()
删除集合 : db.mycollection.drop()
删除数据库 :首先use mydb
命令进入该数据库,然后
db.dropDatabase()
直接从命令提示符或 blash: mongo mydb --eval "db.dropDatabase()
在终端中执行:
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.
打开另一个终端窗口并执行以下命令,
mongodb
use mydb
db.dropDatabase()
该操作的输出应如下所示
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 }
>
请注意, mydb
仍在使用中,因此在那时插入任何输入将再次初始化数据库。