Purpose: to delete collection records / documents in the database. Suppose the collection name is my_collection.
Method used: delete_one () or delete_many ()
- Delete all documents that match the condition . The following operation deletes all documents matching the specified condition.
result = my_collection.delete_many ({"name": "Mr. Geek"})
- To see the number of deleted documents :
print (result.deleted_count)
- Delete all documents:
Method 1: delete all documents using delete_many ()result = my_collection.delete_many ({})
Method 2: delete all documents using collection.remove ()
result = my_collection.remove ()
The best way to remove is to remove the collection so that the data indices are also removed, then create a new collection in that insert data.
- To drop the collection:
db.my_collection.drop ()
First we insert the document into the collection, then we drop the documents as requested.
|
OUTPUT (comment line denoted by #) Connected successfully !!! Data inserted with record ids #Data INSERT {’_id’: ObjectId (’ 5a02227c37b8552becf5ed2b’), ’name’:’ Mr.GfG’, ’eid’: 45,’ location’: ’noida’} {’ _id’: ObjectId (’5a0c734937b8551c1cd03349’),’ name’: ’Mr.Shaurya’,’ eid’: 14, ’location’:’ delhi’} {’_id’: ObjectId (’ 5a0c734937b8551c1cd0334a’), ’name’:’ Mr.Coder ’,’ eid’: 14, ’location’:’ gurugram’} # Mr.Coder is deleted {’_id’: ObjectId (’ 5a02227c37b8552becf5ed2b’), ’name’:’ Mr.GfG’, ’eid’: 45, ’location’:’ noida’} {’_id’: ObjectId (’ 5a0c734937b8551c1cd03349’), ’name’:’ Mr.Shaurya’, ’eid’: 14,’ location’: ’delhi’}