mongodb delete document

‮h‬ttps://www.theitroad.com

To delete a document in a MongoDB collection, you can use the deleteOne() or deleteMany() method. Here are the steps to delete a document using the deleteOne() method:

  1. Open the MongoDB shell: Open a terminal or command prompt and run the mongo command to open the MongoDB shell.

  2. Switch to the database containing the collection you want to delete a document from: Use the use command followed by the name of the database to switch to the database containing the collection. For example, to switch to a database named "mydb", run the following command:

use mydb
  1. Delete the document: Use the deleteOne() method to delete a single document in the collection. For example, to delete a document with the field "name" equal to "John" in a collection named "mycollection", run the following command:
db.mycollection.deleteOne({name: "John"})

The argument to deleteOne() is a filter object that selects the document to delete.

  1. Confirm the document has been deleted: MongoDB will return a message indicating that the document has been deleted. You can also query the collection using the find() method to confirm that the document has been deleted.

Here are the steps to delete multiple documents using the deleteMany() method:

  1. Open the MongoDB shell: Open a terminal or command prompt and run the mongo command to open the MongoDB shell.

  2. Switch to the database containing the collection you want to delete documents from: Use the use command followed by the name of the database to switch to the database containing the collection. For example, to switch to a database named "mydb", run the following command:

use mydb
  1. Delete the documents: Use the deleteMany() method to delete multiple documents in the collection. For example, to delete all documents with the field "age" less than 30 in a collection named "mycollection", run the following command:
db.mycollection.deleteMany({age: {$lt: 30}})

The argument to deleteMany() is a filter object that selects the documents to delete.

  1. Confirm the documents have been deleted: MongoDB will return a message indicating that the documents have been deleted. You can also query the collection using the find() method to confirm that the documents have been deleted.