如果集合存在且存在为空(如何从集合中删除),如何检查PyMongo?

时间:2012-03-22 12:46:25

标签: python mongodb pymongo

如果集合存在且存在为空(如何从集合中删除),如何检入PyMongo? 我试过像

collection.remove()

collection.remove({})

但它不会删除集合。怎么做?

3 个答案:

答案 0 :(得分:51)

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

答案 1 :(得分:17)

您应该使用.drop()代替.remove(),请参阅文档以获取详细信息:http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.drop

=====

很抱歉误解了你的问题。

要检查集合是否存在,请在数据库中使用方法collection_names

>>> collection_name in database.collection_names()

要检查集合是否为空,请使用:

>>> collection.count() == 0

两者都会在结果中返回True或False。

答案 2 :(得分:5)

你试过这个:

db.collection.remove();