Video Transcript (English)
In SQL, we use the DELETE FROM statement with a WHERE clause to determine which records to delete.
For example, in this SQL statement, we’re deleting a record from the sales table, where the id is equal to 1234567.
In MongoDB, this is a very similar process. We use the deleteOne method, which deletes a single document. It takes a filter document and an options object, but we won’t use the options object in the following example.
Let’s translate our SQL example to MongoDB by taking the following steps.
We start with DELETE FROM sales in SQL. In MongoDB, we append the deleteOne method to the sales collection inside our database.
The next part of the SQL statement is WHERE. In MongoDB, we provide a filter document that matches the _id with the ObjectId. Remember, MongoDB uses the _id field as a primary key.
After running this command, we get a message that our command was acknowledged and that one document was deleted.
Deleting a single document is useful, but some cases require us to delete multiple records or documents.
To delete multiple records In SQL, we still use a DELETE FROM statement along with a WHERE clause. We also use an IN clause, which is shorthand for multiple OR conditions.
Here, we’re deleting every store located in Denver or New York.
In MongoDB, we also don’t have to change much about our query. But instead of using the deleteOne method, we use the deleteMany method.
Similar to DELETE FROM in SQL, we can create our query in MongoDB by appending the deleteMany method to the sales collection in our database.
Next, we specify which documents to delete, as we do with WHERE IN in SQL. In MongoDB, we provide a filter that matches all documents with Denver or New York in the store location field.
The $in operator works like the IN clause in SQL. It acts as an “or” statement for the specified field and the values provided in the array.
MongoDB also has an $or operator. While $in is a comparison operator, $or is a logical operator.
Use $in when you want two possible values on the same field.
Use $or when you want any one of the conditions to be true, and it doesn’t have to be on the same field.
Now let’s go back to our query.
When we run the deleteMany query in MongoDB, we get a return message that shows our query was acknowledged and the number of deleted documents from our collection.
If the deleteMany method receives an empty document, it will delete all documents in the collection.
This is similar to SQL behavior when you use DELETE FROM without a WHERE clause.
So don’t forget to include filters in MongoDB, just as you must in SQL.
Awesome job! In this lesson, you learned that the SQL operator to delete is nearly identical to the deleteOne and deleteMany methods in MongoDB.