Document deletion
Command |
Operation |
db.collection.deleteOne() |
Delete a single document that matches a specified filter, even if multiple documents may match the specified filter. |
db.collection.deleteMany() |
Deletes all documents that match the specified filter. |
db.collection.remove() |
Delete a single document or all documents that match a specified filter |
The rest can be consulted here.
Deleteone format
db.collection.deleteOne( <filter>, { writeConcern:<document>, collation:<document> })
Deletes the first document that matches the filter. A Writeerror exception is thrown when used for capped collection.
> db.orders.find().pretty(){ "_id" : ObjectId("563237a41a4d68582c2509da"), "stock" : "Brent Crude Futures", "qty" : 250, "type" : "buy-limit", "limit" : 48.9, "creationts" : ISODate("2015-11-01T12:30:15Z"), "expiryts" : ISODate("2015-11-01T12:35:15Z"), "client" : "Crude Traders Inc."}> try {... db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );... } catch (e) {... print(e);... }{ "acknowledged" : true, "deletedCount" : 1 }> db.orders.find().pretty()>
Delete Date is earlier
> db.orders.find().pretty(){ "_id" : ObjectId("563237a41a4d68582c2509da"), "stock" : "Brent Crude Futures", "qty" : 250, "type" : "buy-limit", "limit" : 48.9, "creationts" : ISODate("2015-11-01T12:30:15Z"), "expiryts" : ISODate("2015-11-01T12:35:15Z"), "client" : "Crude Traders Inc."}> try {... db.orders.deleteOne( { "expiryts" : { $lt: ISODate("2015-11-01T12:40:15Z") } } );... } catch (e) {...
Deletemany format
db.collection.deleteMany( <filter>, { writeConcern:<document>, collation:<document> })
A Writeerror exception is thrown when used for capped collection.
> db.orders.find().pretty(){ "_id" : ObjectId("563237a41a4d68582c2509da"), "stock" : "Brent Crude Futures", "qty" : 250, "type" : "buy-limit", "limit" : 48.9, "creationts" : ISODate("2015-11-01T12:30:15Z"), "expiryts" : ISODate("2015-11-01T12:35:15Z"), "client" : "Crude Traders Inc."}> try {... db.orders.deleteMany( { "client" : "Crude Traders Inc." } );... } catch (e) {... print (e);... }{ "acknowledged" : true, "deletedCount" : 1 }> db.orders.find().pretty()>
Actually, it's almost like deleteone.
Remove format
db.collection.remove( <query>, <justOne>)
Remove all documents from the collection
> db.bios.find().count()10> db.bios.remove( { } )WriteResult({ "nRemoved" : 10 })> db.bios.find().count()0
Delete all documents with matching criteria
> db.products.remove( { qty: { $gt: 20 } } )> db.products.find( { qty: { $gt: 20 } } ).count()0
Use parameter Justone to delete a
> db.products.remove( { qty: { $gt: 20 } }, true )> db.products.find( { qty: { $gt: 20 } } ).count()10
MongoDB crud D