MongoDB
In this MongoDB tutorial we will learn to delete documents.
Login to your MongoDB server and insert the following documents.
For this tutorial I will insert the documents in the subscription collection.
> db.subscription.insertMany([ { "firstname": "John", "lastname": "Doe", "uid": 1, "accountstatus": "ACTIVE", "plan": "TRIAL15DAYS", "modifiedAt": null, "createdAt": new Date() }, { "firstname": "Jane", "lastname": "Doe", "uid": 2, "accountstatus": "ACTIVE", "plan": "PLAN30DAYS", "modifiedAt": null, "createdAt": new Date() }, { "firstname": "Jim", "lastname": "Doe", "uid": 3, "accountstatus": "SUSPENDED", "plan": "PLAN60DAYS", "modifiedAt": null, "createdAt": new Date() }, { "firstname": "Alice", "lastname": "Doe", "uid": 4, "accountstatus": "ACTIVE", "plan": "PLAN1YEAR", "modifiedAt": null, "createdAt": new Date() } ])
Note! We are using new Date() to set the createdAt to current date time.
new Date()
We use the deleteOne method to delete one document from a given collection.
deleteOne
In the following example we are deleting document having uid equal to 4.
> db.subscription.deleteOne({ "uid": 4 })
To delete multiple documents we use the deleteMany method.
deleteMany
In the following example we are deleting documents having uid 2 and 3.
> db.subscription.deleteMany({ "uid": { $in: [2, 3] } })
We can also use the deleteMany method to delete all the documents from a given collection.
In the following example we are deleting all the documents from the subscription collection.
> db.subscription.deleteMany({})