2015-08-27 119 views
0

我正在嘗試迭代集合列表並刪除奶酪數據庫中_id爲'1236'的任何文檔。運行下面的代碼時,沒有任何東西被刪除。但是,邏輯確實在明確使用集合名稱self.db.chips.remove({「_ id」:_ id}))時工作。我究竟做錯了什麼?在mongo DB集合列表中迭代

from pymongo import MongoClient 



class dump: 

    def __init__(self,MONGODB_HOST,MONGODB_PORT,DBS_NAME): 
     self.client = MongoClient(MONGODB_HOST, MONGODB_PORT) 
     self.db = self.client[DBS_NAME] 


    def delete_account(self,_id): 
     names = self.db.collection_names() 
     for name in names: 
      self.db.name.remove({"_id":_id}) 

db1 = dump('localhost',27017,'cheese') 

print db1.delete_account('1236') 
+0

是奶酪db或集合? –

+0

對不起,我犯了一個錯誤。奶酪是一個分貝。芯片是db中的一個集合。 – Mitch

+0

什麼是db.collect? – styvane

回答

1

你有兩個問題有:

  • 在你的for循環的名字是字符串,所以self.db.name.remove({"_id":_id})將導致屬性錯誤。
  • ,所以你需要過濾掉集合與名稱與system.注意點開始不能從system命名空間中刪除。

    def delete_account(self,_id): 
        names = [collection for collection in self.db.collection_names() if not collection.startswith('system.')] 
        for name in names: 
         self.db[name].remove({'_id': _id})