如何检查PyMongo集合是否存在以及是否为空(从集合中全部删除)? [英] How to check in PyMongo if collection exists and if exists empty (remove all from collection)?

查看:1487
本文介绍了如何检查PyMongo集合是否存在以及是否为空(从集合中全部删除)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在PyMongo中检入集合是否存在以及是否为空(从集合中全部删除)? 我尝试过

How to check in PyMongo if collection exists and if exists empty (remove all from collection)? I have tried like

collection.remove()

collection.remove({})

,但不会删除收藏集.该怎么做?

but it doesn't delete collection. How to do that ?

推荐答案

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

这篇关于如何检查PyMongo集合是否存在以及是否为空(从集合中全部删除)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆