Skip to content

Latest commit

 

History

History
executable file
·
42 lines (34 loc) · 1.43 KB

File metadata and controls

executable file
·
42 lines (34 loc) · 1.43 KB

4.5.5 删除文档

remove()

MongoDB 利用 remove() 方法 清除集合中的文档。它有 2 个可选参数:

  • deletion criteria:(可选)删除文档的标准。
  • justOne:(可选)如果设为 true 或 1,则只删除一个文档。
> db.swiftdb.remove({"tags": "iOS"})

WriteResult({ "nRemoved" : 1 })

> db.swiftdb.find().pretty()

{ "_id" : ObjectId("580ebd569ab3b93e870f44fd"), "name" : "GitHub" }
{ "_id" : ObjectId("580ec0429ab3b93e870f44ff") }
{ "_id" : ObjectId("580ec0479ab3b93e870f4500") }
{ "_id" : ObjectId("580ec04b9ab3b93e870f4501") }
{ "_id" : ObjectId("580ec04d9ab3b93e870f4502") }
{ "_id" : ObjectId("580ec0579ab3b93e870f4503") }
{ "_id" : ObjectId("580ec0659ab3b93e870f4504") }
{ "_id" : ObjectId("580ec0699ab3b93e870f4505") }
{ "_id" : ObjectId("580ec06b9ab3b93e870f4506") }
{ "_id" : ObjectId("580ec06d9ab3b93e870f4507") }

只删除一个文档

如果有多个记录,而你只想删除第一条记录,那么就设置 remove() 方法中的 justOne 参数:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

删除所有文档

如果没有指定删除标准,则 MongoDB 会将集合中所有文档都予以删除。

> db.swiftdb.remove({})
WriteResult({ "nRemoved" : 10 })
> db.swiftdb.find().pretty()
> 

想要删除一个集合里的所有文档,建议使用 drop() 方法,它删除包括索引的整个集合是更加高效的,然后重建集合和索引。