Python MongoDB Delete Document

In MongoDB, you can delete documents from a collection using the following methods in PyMongo:

  1. delete_one(): Deletes a single document that matches the query.
  2. delete_many(): Deletes multiple documents that match the query.
  3. drop(): Deletes the entire collection.

1. Deleting a Single Document

The delete_one() method deletes the first document that matches the query.

Syntax:

collection.delete_one(query)
  • query: The condition used to find the document to be deleted.

Example:

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]

# Delete the first document where the name is "John"
query = { "name": "John" }
result = mycol.delete_one(query)

print(f"Documents deleted: {result.deleted_count}")

2. Deleting Multiple Documents

The delete_many() method deletes all documents that match the query.

Syntax:

collection.delete_many(query)
  • query: The condition used to find the documents to be deleted.

Example:

# Delete all documents where 'age' is greater than 25
query = { "age": { "$gt": 25 } }
result = mycol.delete_many(query)

print(f"Documents deleted: {result.deleted_count}")

3. Deleting All Documents

If you want to delete all documents in a collection, you can use an empty query ({}) with delete_many().

Example:

# Delete all documents in the collection
result = mycol.delete_many({})

print(f"Documents deleted: {result.deleted_count}")

4. Dropping the Entire Collection

To remove an entire collection (including all documents and metadata), you can use the drop() method.

Example:

# Drop the collection
mycol.drop()

print("Collection dropped!")

Full Example of Deleting Documents

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]

# Insert some sample documents (if not already inserted)
mycol.insert_many([
    { "name": "John", "age": 28, "address": "123 Elm Street" },
    { "name": "Amy", "age": 32, "address": "456 Oak Street" },
    { "name": "Mark", "age": 25, "address": "789 Maple Avenue" },
    { "name": "Sara", "age": 24, "address": "101 Pine Road" }
])

# Delete one document where 'name' is 'John'
query = { "name": "John" }
result = mycol.delete_one(query)
print(f"Documents deleted: {result.deleted_count}")

# Delete multiple documents where 'age' is greater than 25
query = { "age": { "$gt": 25 } }
result = mycol.delete_many(query)
print(f"Documents deleted: {result.deleted_count}")

# Drop the entire collection
mycol.drop()
print("Collection dropped!")

Summary:

  • delete_one(): Deletes the first document that matches the query.
  • delete_many(): Deletes all documents that match the query.
  • drop(): Deletes the entire collection.
Leave a Reply 0

Your email address will not be published. Required fields are marked *