定义
db.collection.drop(<options>)带驱动程序的 MongoDB
This page documents a mongosh method. To see the equivalent method in a MongoDB driver, see the corresponding page for your programming language:从数据库中删除集合或视图。该方法还会删除与删除的集合关联的任何索引。
drop()是drop命令的包装器。返回: true
注意
如果指定的集合不存在, db.collection.drop() 仍返回 true。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
drop()方法采用以下形式:
db.collection.drop( { writeConcern: <document> } )
drop() 方法接受带有以下字段的可选文档:
字段 | 说明 |
|---|---|
writeConcern | 可选.表达 When issued on a sharded cluster, |
行为
The
db.collection.drop()method anddropcommand abort any in-progress index builds on the target collection before dropping the collection.对于副本集或分片副本集,中止主节点上的索引不会同时中止从节点索引构建。MongoDB 尝试中止主节点上指定索引正在进行的构建。如果成功,则会创建关联的
abortoplog 条目。从节点如果有正在进行的构建的副本,则在提交或中止索引构建之前会等待来自主节点的提交或中止 oplog 条目。删除集合将删除其关联的区域/标记范围。
从MongoDB5.0 开始,如果您尝试从
drop删除管理员数据库或配置数据库中的集合,db.collection.drop()mongos命令和 方法会返回错误。要删除这些集合,请连接到配置服务器并在其中运行命令。从 MongoDB 6.0 开始,
drop()会删除指定的集合以及与加密字段相关的所有内部集合。重要
mongoshdrop()方法的行为与驱动程序drop方法的行为不同。驱动程序的连接必须启用自动加密,才能删除指定的集合以及与加密字段相关的任何内部集合。mongosh始终删除指定的集合以及与加密字段相关的任何内部集合。
在分片集群上重用已删除的集合名称
对于运行 MongoDB 5.0 或更高版本的分片集群,无需执行任何特殊动作。使用 drop() 方法,然后创建具有相同名称的新集合。
资源锁定
db.collection.drop() obtains an exclusive lock on the specified collection for the duration of the operation. All subsequent operations on the collection must wait until db.collection.drop() releases the lock.
例子
使用默认写关注来删除集合
以下操作会删除当前数据库中的 students 集合。
db.students.drop()
使用 w: 1 写关注删除集合
以下操作会删除当前数据库中的 students 集合。该操作使用 1 写关注:
db.students.drop( { writeConcern: { w: 1, j: true } } )