How to check in PyMongo if collection exists and if exists empty (remove all from collection)? I have tried like
collection.remove()
or
collection.remove({})
but it doesn't delete collection. How to do that ?
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
Use the drop_database() method to delete a MongoDB database with PyMongo. NOTE: This API call does not return a results object to verify that the call was successful. If you try assigning a variable to the method call, it will just return a NoneType object.
To delete all documents that match a deletion criteria, pass a filter parameter to the deleteMany() method. The method returns a document with the status of the operation. For more information and examples, see deleteMany() .
Sample code in Pymongo with comment as explanation:
from pymongo import MongoClient connection = MongoClient('localhost', 27017) #Connect to mongodb print(connection.database_names()) #Return a list of db, equal to: > show dbs db = connection['testdb1'] #equal to: > use testdb1 print(db.list_collection_names()) #Return a list of collections in 'testdb1' print("posts" in db.list_collection_names()) #Check if collection "posts" # exists in db (testdb1) collection = db['posts'] print(collection.count() == 0) #Check if collection named 'posts' is empty collection.drop() #Delete(drop) collection named 'posts' from db and all documents contained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With