你的位置:首页 > 数据库

[数据库]MongoDB快速入门学习笔记6 MongoDB的文档删除操作

db.集合名称.remove({query}, justOne)
query:过滤条件,可选
justOne:是否只删除查询到的第一条数据,值为true或者1时,只删除一条数据,默认为false,可选。


准备数据:把_id为1和2的age都变成28

> db.student.update({_id:1},{$set:{age:28}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.student.update({_id:2},{$set:{age:28}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.student.find(){ "_id" : 1, "name" : "zhangsan", "age" : 28 }{ "_id" : 2, "name" : "lisi", "age" : 28 }{ "_id" : 3, "name" : "wangwu", "age" : 30 }{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }{ "_id" : 5, "name" : "qianliu", "age" : 33 }{ "_id" : 6, "name" : "sunba", "age" : 32 }{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] }

 

1、使用两个参数:
删除age=28的第一条数据

> db.student.remove({age:28}, true)WriteResult({ "nRemoved" : 1 })> db.student.find(){ "_id" : 2, "name" : "lisi", "age" : 28 }{ "_id" : 3, "name" : "wangwu", "age" : 30 }{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }{ "_id" : 5, "name" : "qianliu", "age" : 33 }{ "_id" : 6, "name" : "sunba", "age" : 32 }{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] }

 

2、使用一个参数:
删除age=28的所有数据

> db.student.remove({age:28})WriteResult({ "nRemoved" : 2 })> db.student.find(){ "_id" : 3, "name" : "wangwu", "age" : 30 }{ "_id" : 5, "name" : "qianliu", "age" : 33 }{ "_id" : 6, "name" : "sunba", "age" : 32 }{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] }

 

3、删除集合的全部数据,括号中的“{}”必须有,表示空的过滤条件:

> db.student.remove({})WriteResult({ "nRemoved" : 4 })

 

另外使用remove()方法删除的时候,只是删除数据,表还会存在。使用drop()方法会把表也删除,并且drop()的效率要比remove()效率高很多。