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 ?
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.
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.
collection_names
is deprecated. Use list_collection_names
instead
Commented
Oct 3, 2019 at 10:03
DROP TABLE
.
Have you tried this:
db.collection.remove();