MongoDB:删除操作

 

一. 根据查询条件删除文档

  1. 查询 id=1 的所有文档
test:PRIMARY> db.test_1.find({id:1})
{ "_id" : ObjectId("58a11caca14d421caf8c45db"), "id" : 1, "name" : "name_1" }
{ "_id" : ObjectId("58a11cada14d421caf8c45dc"), "id" : 1, "name" : "swrd" }
  1. 删除 id=1 的所有文档,查看里面已无id等于1的数据
test:PRIMARY> db.test_1.remove({id:1})
WriteResult({ "nRemoved" : 2 })
test:PRIMARY> db.test_1.find({id:1})
test:PRIMARY>

二. 删除一个集合中的所有文档

  1. 查询 test_1 集合的所有文档
test:PRIMARY> db.test_1.find()
{ "_id" : ObjectId("58a11dd8a14d421caf8c45dd"), "id" : 2, "name" : "name_2" }
{ "_id" : ObjectId("58a11dd8a14d421caf8c45de"), "id" : 3, "name" : "name_3" }
{ "_id" : ObjectId("58a11dd8a14d421caf8c45df"), "id" : 4, "name" : "name_4" }
{ "_id" : ObjectId("58a11dd8a14d421caf8c45e0"), "id" : 5, "name" : "name_5" }
{ "_id" : ObjectId("58a11dd8a14d421caf8c45e1"), "id" : 6, "name" : "name_6" }
{ "_id" : ObjectId("58a11dd8a14d421caf8c45e2"), "id" : 7, "name" : "name_7" }
  1. 删除 test_1 集合的所有文档
test:PRIMARY> db.test_1.remove({})
WriteResult({ "nRemoved" : 6 })
test:PRIMARY> db.test_1.find()

三、删除集合

test:PRIMARY> show tables;
test_1
test_2
test_3
test_4
test:PRIMARY> db.test_4.drop()
true
test:PRIMARY> show tables;
test_1
test_2
test_3

四、删除数据库

test:PRIMARY> show dbs
local          0.000GB
log            0.089GB
student        0.000GB
swrd           0.000GB
test           0.000GB
test:PRIMARY> db
test
test:PRIMARY> db.test.getDB()
test
test:PRIMARY> show tables;
test_1
test:PRIMARY> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
test:PRIMARY> show dbs
local          0.000GB
log            0.089GB
student        0.000GB
swrd           0.000GB

在执行删除整个数据库前,要谨慎,执行db命令查看当前的使用的数据库,可确保误删除,造成数据的丢失.

 
 
 
posted @   小雨淅淅o0  阅读(222)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示