37

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 ?

Florian Winter
  • 4,750
  • 1
  • 44
  • 69
Damir
  • 54,277
  • 94
  • 246
  • 365

3 Answers3

72

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. 
EwyynTomato
  • 4,009
  • 1
  • 31
  • 39
  • do you really want to be querying all collections in the database every time you want to check if the collection exists? – Moataz Elmasry Feb 19 '18 at 09:48
  • 1
    @MoatazElmasry, method for checking if collection exists has not yet been implemented in mongodb, you can check on this issue: https://jira.mongodb.org/browse/SERVER-1938 – EwyynTomato Feb 25 '18 at 03:42
  • @MoatazElmasry meanwhile, if you really need to optimize the performance of you application, you can resort to other techniques such as pre-caching collection results. – EwyynTomato Feb 25 '18 at 03:45
20

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.

Reorx
  • 2,801
  • 2
  • 24
  • 29
5

Have you tried this:

db.collection.remove();

Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
geakie
  • 1,458
  • 9
  • 9
  • db.collection.remove() only removes all records from collection that matches the query given in remove. Eg db.collection.remove({name: 'abc'}) will remove all records with name 'abc', empty query in remove will cause all records to be removed, but collection will stay as it is. – Dania Feb 12 '18 at 13:17