2012-03-22 161 views

回答

4

你有沒有嘗試過這樣的:在Pymongo

db.collection.remove();

+0

db.collection.remove()只收集與查詢匹配刪除所有記錄在刪除中給出。如db.collection.remove({名稱:「ABC」})將刪除所有記錄名爲「ABC」,空的查詢中刪除將導致刪除所有記錄,但集合將保持原樣。 – Dania 2018-02-12 13:17:10

36

示例代碼爲說明註釋:

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 
+0

你真的想你想檢查集合存在,每次都要查詢所有集合在數據庫中? – 2018-02-19 09:48:15

+0

@MoatazElmasry,以檢查是否存在收集尚未MongoDB中被實現的方法,你可以檢查這個問題:https://jira.mongodb.org/browse/SERVER-1938 – EwyynTomato 2018-02-25 03:42:11

+0

@MoatazElmasry同時,如果你真的需要優化應用程序的性能,您可以使用其他技術,例如預緩存收集結果。 – EwyynTomato 2018-02-25 03:45:18