2015-08-27 122 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})