且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查PyMongo集合是否存在以及是否为空(从集合中全部删除)?

更新时间:2023-11-25 11:09:40

Pymongo中的示例代码,并带有注释作为解释:

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