Python Mongodb – Delete_many()

MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model.

Delete_many()

Delete_many() is used when one needs to delete more than one document. A query object containing which document to be deleted is created and is passed as the first parameter to the delete_many().

Sample Database:

python-mongodb-delete-many-1

Example 1: Deleting all the documents where the name starts with ‘A’.



filter_none

edit
close

play_arrow

link
brightness_4
code

import pymongo
  
  
client = pymongo.MongoClient("mongodb://localhost:27017/")
  
# Connecting to the database
mydb = client["GFG"]
  
# Connecting the to collection
col = mydb["Geeks"]
  
query = {"Name": {"$regex": "^A"}}
d = col.delete_many(query)
  
print(d.deleted_count, " documents deleted !!")

chevron_right


Output:

2  documents deleted !!

MongoDB Shell:

python-mongodb-delet-many-2

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymongo
  
  
client = pymongo.MongoClient("mongodb://localhost:27017/")
  
# Connecting to the database
mydb = client["GFG"]
  
# Connecting the to collection
col = mydb["Geeks"]
  
query = {"Class": '3'}
d = col.delete_many(query)
  
print(d.deleted_count, " documents deleted !!")

chevron_right


Output:

1  documents deleted !!

MongoDB Shell:

python-mongodb-delete-many-3

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.