从bash提示符中最简单的方法是什么?


当前回答

在终端执行:

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.

其他回答

我发现这很容易记住:

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 }

使用python删除MongoDB数据库:

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")

你也可以使用"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。

您可以先切换到要删除的数据库。然后您可以使用命令dropDatabase()删除相同的。

代码:

>用dbName

>db.dropdataBase()

结果将是:

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

如果要删除数据库中的特定集合,则切换到数据库并输入以下命令。

代码:

>用dbName

db.collection.drop ()

结果将是:

true

如果你想更好地理解MongoDB shell命令,它是 最好始终遵循文档。 文档链接: https://www.mongodb.com/docs/manual/reference/method/#std-label-js-administrative-methods

打开终端,输入:

mongo 

下面的命令应该显示列出的数据库:

show dbs 

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

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

终端输出如下:

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