如何在PyMongo中删除MongoDB集合

2022-03-14 00:00:00 python mongodb pymongo

问题描述

如何签入PyMongo(如果存在集合以及存在时为空)(全部从集合中删除)? 我试过了

collection.remove()

collection.remove({})

但它不会删除集合。如何做到这一点?


解决方案

Pymongo示例代码,注释作为说明:

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. 

相关文章