Damir
Damir

Reputation: 56249

How to delete a MongoDB collection in PyMongo

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 ?

Upvotes: 37

Views: 56723

Answers (3)

EwyynTomato
EwyynTomato

Reputation: 4077

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. 

Upvotes: 72

Reorx
Reorx

Reputation: 3001

You should use .drop() instead of .remove(), see documentation for detail: http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.drop

=====

Sorry for misunderstanding your question.

To check if a collection exists, use method collection_names on database:

>>> collection_name in database.list_collection_names()

To check if a collection is empty, use:

>>> collection.count() == 0

both will return True or False in result.

Upvotes: 21

Gregor
Gregor

Reputation: 1468

Have you tried this:

db.collection.remove();

Upvotes: 5

Related Questions