【MongoDB】删除文档
MongoDB使用remove()方法移除集合中的文档
【语法】
1 2 3 4 5 6 7 8 |
db.collection.remove( <query>, { justOne: <boolean>, writeConcern: <document>, collation: <document> } ) |
参数 | 类型 | 描述 |
---|---|---|
query | document | (可选)删除的文档的条件。 |
justOne | boolean | (可选)如果设为 true 或 1,则只删除一个文档。 |
writeConcern | document | (可选)抛出异常的级别。 |
1:删除测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
> db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("598164a5c566b07b8733e778"), "name" : "lisi", "age" : 22, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e779"), "name" : "zhaosi", "age" : 50, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e77a"), "name" : "liuneng" } { "_id" : ObjectId("59816629c566b07b8733e77b"), "name" : "zhaosi", "sex" : 0 } { "_id" : ObjectId("598179bf33eff8385847b994"), "name" : "ml", "sex" : 0 } > # 删除集合t中name为zhaosi的文档,因为有两条,所以此操作将两条全部干掉 > db.t.remove({"name":"zhaosi"}) WriteResult({ "nRemoved" : 2 }) > # 验证 > db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("598164a5c566b07b8733e778"), "name" : "lisi", "age" : 22, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e77a"), "name" : "liuneng" } { "_id" : ObjectId("598179bf33eff8385847b994"), "name" : "ml", "sex" : 0 } > |
2:justOne参数测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# 修改下环境,使集合t中有两条name相同的文档 > db.t.update({"name" : "lisi"},{$set:{"name" : "liuneng"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("598164a5c566b07b8733e778"), "name" : "liuneng", "age" : 22, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e77a"), "name" : "liuneng" } { "_id" : ObjectId("598179bf33eff8385847b994"), "name" : "ml", "sex" : 0 } > # 删除name为liuneng的文档,justOne为true(或者为1),意思只删除第一条 > db.t.remove({"name":"liuneng"},true) WriteResult({ "nRemoved" : 1 }) > # 验证 > db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e77a"), "name" : "liuneng" } { "_id" : ObjectId("598179bf33eff8385847b994"), "name" : "ml", "sex" : 0 } > |
3:全部清空
1 2 3 4 5 |
> db.t.remove({}) WriteResult({ "nRemoved" : 3 }) > > db.t.find() > |