db.集合名稱.remove({query}, justOne)query:過濾條件,可選justOne:是否只刪除查詢到的第一條數據,值為true或者1時,只刪除一條數據,預設為false,可選。 準備數據:把_id為1和2的age都變成28 1、使用兩個參數:刪除age=28的第一條數據 2、使 ...
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()效率高很多。