Delete one or more documents from a MongoDB collection using PyMongo

Overview:

  • A MongoDB collection consists of several JSON documents in binary format.
  • To delete records from a MongoDB collection, the PyMongo Python driver offers several variants of delete operation through the methods
    • delete_one()
    • delete_many()

Delete one document satisfying a filter condition:

  • To delete only one document, that meets the specified filter conditionamong several others, the method can be called on a object.
  • The example below specifies the condition for the single document that is to be deleted is {"red" : 123, "green" : 223}.

Example:

# import the python driver for MongoDB

from pymongo import MongoClient

 

# Create a MongoDB client

mongoDBConnection   = MongoClient('mongodb://localhost:27017/')

 

# Get a collection instance

database        = mongoDBConnection.sample

collection      = database.sample1

 

# Print the collection before deleting a single record meeting the criteria

print("Before deletion:");

for mongoDBdocument in collection.find():

    print(mongoDBdocument)

 

# Delete one record satisfying the filter condition

deleteResult    = collection.delete_one({"red" : 123, "green" : 223})

 

print("Number of documents deleted from the MongoDB collection:")

print(deleteResult.deleted_count)

 

# Print the collection after deleting a single record meeting the criteria

print("After deletion:");

for mongoDBdocument in collection.find():

    print(mongoDBdocument)

 

Output:

Before deletion:

{'_id': ObjectId('5ab9fad002334a0303b029c1'), 'color1': 'red', 'color2': 'blue'}

{'_id': ObjectId('5ab9fb8302334a031cc2fc14'), 'red': 146, 'green': 46, 'blue': 246}

{'_id': ObjectId('5aba309f74d9af6fff2f2209'), 'red': 123.0, 'green': 223.0, 'blue': 23.0}

Number of documents deleted from the MongoDB collection:

1

After deletion:

{'_id': ObjectId('5ab9fad002334a0303b029c1'), 'color1': 'red', 'color2': 'blue'}

{'_id': ObjectId('5ab9fb8302334a031cc2fc14'), 'red': 146, 'green': 46, 'blue': 246}

 

Deleting multiple documents satisfying a filter condition:

  • To delete multiple documents from a MongoDB collection the db.collection.deletemany()method can be used.
  • db.collection.deletemany()can be passed with a JSON document specifying the filter condition. This method removes all the documents matching the specified filter condition.
  • If the filter condition is empty the method db.collection.deletemany()removes all the documents from the document collection.

Example:

# import the python driver for MongoDB

from pymongo import MongoClient

 

# Create a MongoDB client

mongoDBConnection   = MongoClient('localhost', 27017)

 

# Get a collection instance

collection        = mongoDBConnection.sample.orders

 

# Print the collection before deleting a single record meeting the criteria

print("Before deletion:");

for mongoDBdocument in collection.find():

    print(mongoDBdocument)

 

# Delete all the order records which are in cancelled state

deleteResult    = collection.delete_many({"Status" : "Cancelled"})

 

print("Number of documents deleted from the MongoDB collection:")

print(deleteResult.deleted_count)

 

# Print the collection after deleting a single record meeting the criteria

print("After deletion:");

for mongoDBdocument in collection.find():

    print(mongoDBdocument)

 

Output:

Before deletion:

{'_id': ObjectId('5aba593174d9af6fff2f2213'), 'OrderId': '536728', 'Symbol': 'MSFT', 'Side': 'Buy', 'Qty': '100', 'Price': '91.95', 'Venue': 'NasdaqGS', 'Status': 'Ordered', 'TimeStamp': '1522161353'}

{'_id': ObjectId('5aba596374d9af6fff2f2216'), 'OrderId': '536821', 'Symbol': 'GOOG', 'Side': 'Sell', 'Qty': '50', 'Price': '1147.01', 'Venue': 'NasdaqGS', 'Status': 'Cancelled', 'TimeStamp': '1522161363'}

{'_id': ObjectId('5aba597274d9af6fff2f2217'), 'OrderId': '536841', 'Symbol': 'AMZN', 'Side': 'Sell', 'Qty': '50', 'Price': '1668.87', 'Venue': 'NasdaqGS', 'Status': 'Cancelled', 'TimeStamp': '1522161461'}

Number of documents deleted from the MongoDB collection:

2

After deletion:

{'_id': ObjectId('5aba593174d9af6fff2f2213'), 'OrderId': '536728', 'Symbol': 'MSFT', 'Side': 'Buy', 'Qty': '100', 'Price': '91.95', 'Venue': 'NasdaqGS', 'Status': 'Ordered', 'TimeStamp': '1522161353'}

 


Copyright 2024 © pythontic.com