遍历 mongo 数据库集合的列表

Iterating over a list of mongo DB collections

我正在尝试遍历集合列表并删除奶酪数据库中 _id 为“1236”的所有文档。当 运行 以下代码时,不会删除任何内容。但是,当显式使用集合名称 self.db.chips.remove({"_id":_id})) 时,逻辑确实有效。我做错了什么?

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')

你有两个问题:

  • 在您的 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})