如何PyMongo檢查集合存在,如果存在空(刪除所有來自集合)? 我試圖像如何PyMongo檢查集合存在,如果存在空(刪除所有來自集合)?
collection.remove()
或
collection.remove({})
,但它不會刪除集合。怎麼做 ?
如何PyMongo檢查集合存在,如果存在空(刪除所有來自集合)? 我試圖像如何PyMongo檢查集合存在,如果存在空(刪除所有來自集合)?
collection.remove()
或
collection.remove({})
,但它不會刪除集合。怎麼做 ?
您應該使用.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
都返回真或假的結果。
你有沒有嘗試過這樣的:在Pymongo
db.collection.remove();
示例代碼爲說明註釋:
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.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
你真的想你想檢查集合存在,每次都要查詢所有集合在數據庫中? – 2018-02-19 09:48:15
@MoatazElmasry,以檢查是否存在收集尚未MongoDB中被實現的方法,你可以檢查這個問題:https://jira.mongodb.org/browse/SERVER-1938 – EwyynTomato 2018-02-25 03:42:11
@MoatazElmasry同時,如果你真的需要優化應用程序的性能,您可以使用其他技術,例如預緩存收集結果。 – EwyynTomato 2018-02-25 03:45:18
db.collection.remove()只收集與查詢匹配刪除所有記錄在刪除中給出。如db.collection.remove({名稱:「ABC」})將刪除所有記錄名爲「ABC」,空的查詢中刪除將導致刪除所有記錄,但集合將保持原樣。 – Dania 2018-02-12 13:17:10