对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

dropDatabase(数据库命令)

dropDatabase

The dropDatabase command drops the current database, deleting the associated data files.

此命令可用于以下环境中托管的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

注意

所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

该命令具有以下语法:

db.runCommand(
{
dropDatabase: 1,
writeConcern: <document>,
comment: <any>
}
)

该命令采用以下可选字段:

字段
说明

writeConcern

可选。 表达大于 时要使用的 写关注(write"majority" concern) 的文档

{ w: <value>, j: <boolean>, wtimeout: <number> }

省略使用 "majority" 的默认/最小写入关注。

当在副本集上发出时,如果指定的写关注(write concern)导致成员确认少于写关注(write concern)"majority" ,则该操作使用"majority" 。否则,使用指定的写关注(write concern)。

在分片集群上发出时,MongoDB 会将指定的写关注转换为 "majority"

另请参阅行为

comment

可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:

注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。

mongosh also provides the helper method db.dropDatabase().

该操作仅采用独占 (X) 数据库锁。

该命令不会删除与当前数据库相关联的用户。要删除相关用户,请在要删除的数据库中运行 dropAllUsersFromDatabase 命令。

The db.dropDatabase() method and dropDatabase command abort any in-progress index builds on collections in the target database before dropping the database. Aborting an index build has the same effect as dropping the built index.

对于副本集或分片副本集,中止主节点上的索引不会同时中止从节点索引构建。MongoDB 尝试中止主节点上指定索引正在进行的构建。如果成功,则会创建关联的 abort oplog 条目。节点如果有正在进行的构建的副本,则在提交或中止索引构建之前会等待来自主节点的提交或中止 oplog 条目。

副本集

At minimum, dropDatabase waits until all collections drops in the database have propagated to a majority of the replica set members (i.e. uses the write concern "majority").

如果您指定需要少数人确认的写关注,则该命令使用写关注"majority"

如果您指定需要大多数人确认的写关注(write concern),则该命令将使用指定的写关注(write concern)。

分片集群

在分片集群上发出时,MongoDB 会将指定的写关注转换为 "majority"

If you intend to create a new database with the same name as the dropped database, you must run the dropDatabase command on a mongos.

这样可以确保所有集群节点刷新其元数据缓存,其中包括新数据库主分片的位置。否则,您可能会在读取时丢失数据,并且可能无法将数据写入正确的分片。要恢复,您必须手动干预。

从MongoDB5.0 开始,如果您尝试从dropDatabase 删除管理员数据库或配置数据库,db.dropDatabase() 命令和mongos 方法会返回错误。

警告

删除管理数据库配置数据库可能会使您的集群处于不可用状态。

The db.dropDatabase() method and dropDatabase create an invalidate Event for any MongoDB Change Streams opened on the dropped database or opened on the collections in the dropped database.

The following example in mongosh uses the use <database> operation to switch the current database to the temp database and then uses the dropDatabase command to drop the temp database:

use temp
db.runCommand( { dropDatabase: 1 } )