定义
dropDatabaseThe
dropDatabasecommand drops the current database, deleting the associated data files.
兼容性
此命令可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
该命令具有以下语法:
db.runCommand( { dropDatabase: 1, writeConcern: <document>, comment: <any> } )
命令字段
该命令采用以下可选字段:
字段 | 说明 | |
|---|---|---|
| 可选。 表达大于 时要使用的 写关注(write 省略使用 当在副本集上发出时,如果指定的写关注(write concern)导致成员确认少于写关注(write concern) 在分片集群上发出时,MongoDB 会将指定的写关注转换为 另请参阅行为。 | |
| 可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
注释可以是任何有效的 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,
dropDatabasewaits 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
dropDatabasecommand on amongos.这样可以确保所有集群节点刷新其元数据缓存,其中包括新数据库主分片的位置。否则,您可能会在读取时丢失数据,并且可能无法将数据写入正确的分片。要恢复,您必须手动干预。
从MongoDB5.0 开始,如果您尝试从
dropDatabase删除管理员数据库或配置数据库,db.dropDatabase()命令和mongos方法会返回错误。
Change Streams
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 } )