How to check in PyMongo if collection exists and if exists empty (remove all from collection)?

Damir picture Damir · Mar 22, 2012 · Viewed 43.4k times · Source

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 ?

Answer

EwyynTomato picture EwyynTomato · Mar 22, 2012

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.