DEV Community

Full Stack Hacker
Full Stack Hacker

Posted on • Edited on

1 1

Delete data in MongoDB (part 1)

The deleteOne() method allows you to delete a single document from a collection.

The deleteOne() method has the following syntax:

db.collection.deleteOne(filter, option)

The deleteOne() method accepts two arguments:

  • filter is an required argument. The filter is a document that specifies the condition for matching the document to remove. If you pass an empty document {} into the method, it’ll delete the first document in the collection.
  • option is an optional argument. The option is a document that specifies the deletion options.

Launch mongo shell from the Terminal on Linux and connect to the productdb database on the local MongoDB server: mongosh productdb We’ll use the following products collection for the projection examples:

db.products.insertMany([
    { "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256],"inventory":[{ qty: 1200,"warehouse": "San Jose"}]},
    { "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512],"inventory":[{ qty: 300,"warehouse": "San Francisco"}]},
    { "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128],"inventory":[{ qty: 400,"warehouse": "San Jose"},{ qty: 200,"warehouse": "San Francisco"}]},
    { "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024],"inventory":[{ qty: 1200,"warehouse": "San Mateo"}]},
    { "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 5.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
 ])

Using the deleteOne() method to delete a single document

The following example uses the deleteOne() method to delete a document with the _id is 1 from the products collection:

db.products.deleteOne({ _id: 1 })

The deleteCount field returned 1 indicating the number of deleted documents.

Using the deleteOne() method to delete the first document from a collection

The following query uses the deleteOne() method to remove the first document returned from the products collection:

db.products.deleteOne({})

Top comments (0)

Retry later
Retry later