Dam*_*mir 26 python mongodb pymongo
如果集合存在且存在为空(如何从集合中删除),如何检查PyMongo?我试过像
collection.remove()
Run Code Online (Sandbox Code Playgroud)
要么
collection.remove({})
Run Code Online (Sandbox Code Playgroud)
但它不会删除集合.怎么做 ?
Ewy*_*ato 54
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
Run Code Online (Sandbox Code Playgroud)
Reo*_*orx 18
您应该使用.drop()
而不是.remove()
,请参阅文档详细信息:http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.drop
=====
很抱歉误解了你的问题.
要检查集合是否存在,请collection_names
在数据库上使用方法:
>>> collection_name in database.list_collection_names()
Run Code Online (Sandbox Code Playgroud)
要检查集合是否为空,请使用:
>>> collection.count() == 0
Run Code Online (Sandbox Code Playgroud)
两者都会在结果中返回True或False.
归档时间: |
|
查看次数: |
35837 次 |
最近记录: |