Mitch
Mitch

Reputation: 177

Iterating over a list of mongo DB collections

I'm trying to iterate over a list of collections and remove any document with the _id of '1236' in the cheese db. When running the code below, nothing gets deleted. The logic does, however, work when explicitly use a collection's name self.db.chips.remove({"_id":_id})). What am i doing wrong?

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

Upvotes: 0

Views: 970

Answers (1)

Sede
Sede

Reputation: 61225

You have two problems there:

  • In your for loop name is string so self.db.name.remove({"_id":_id}) will result in attribute error.
  • You can't delete from system namespace so you need to filter out collection with name starts with system. note the dot.

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

Upvotes: 1

Related Questions