Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 919
Damir Avatar asked Mar 22 '12 12:03

Damir


People also ask

How do you delete a collection in MongoDB?

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.

How do I delete DB PyMongo?

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.

How do I delete everything in MongoDB?

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() .


1 Answers

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.  
like image 52
EwyynTomato Avatar answered Sep 30 '22 21:09

EwyynTomato