Deleting documents
1. Deleting documents
Welcome back! In this lesson, we’ll look at how to delete documents from a MongoDB collection. This is useful for removing outdated entries, cleaning up test data, or handling user deletions.2. Deleting a single document
To delete a single document, use .delete_one(). Just like with .find_one(), you target the document using a filter. In this case, we’re deleting a movie titled gladiator. MongoDB returns a result object. You can check deleted_count to confirm whether anything was actually removed. If it’s 1, the deletion was successful. If it’s 0, no matching document was found. And just like with .find_one() and .update_one(), if your filter matches multiple documents, only the first matching document will be removed.3. Removing multiple documents at the same time
Need to delete more than one document at once? Use .delete_many(). It works just like .find(): pass in a filter, and MongoDB will remove all documents that match. In this example, we’re deleting every movie with a rating below 5. Just like before, the result includes deleted_count, which tells you how many documents were removed, 4 in this case. A quick word of caution: deletion is permanent! There’s no undo! So always double-check your filter before running a bulk delete. In the DataCamp exercises, you can easily reset your database to its original state, so you can delete documents to your heart's desire.4. Let's practice!
Now it’s your turn to use .delete_one() and .delete_many() and remove documents from your collection. Good luck.Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.