Pendelluft
Pendelluft

Reputation: 99

Interpret 'collection' in db.collection.drop() as variable vs. set database

I'm trying to iterate through a list of collections within a MongoDB 3.4 database and perform updates and deletions. I'm trying to make the code interpret 'collection' as a string variable, but the code believes it is a single database:

for collection in db.collection_names():
    if collection[-3:] == "_CS":
        request = [UpdateMany({},{"$set": {"Collection": collection}})]
        result = db.collection.bulk_write(request)

    else:
        db.collection.drop() 

Is there an alternative way to delete a collection through Python/Pymongo that takes the name of the collection as an argument, or is there a way to parse 'collection' so that the interpreter realizes it's a variable?

Upvotes: 1

Views: 67

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

In the loop block the collection name is bound to a str object.

Dictionary style indexing is useful here to access the collection with the collection name. e.g.

for collection in db.collection_names():
    if collection[-3:] == "_CS":
        request = [UpdateMany({},{"$set": {"Collection": collection}})]
        result = db[collection].bulk_write(request)

    else:
        db[collection].drop()

Or, use the get_collection method of the pymongo.database.Database instance.

for collection in db.collection_names():
    if collection[-3:] == "_CS":
        request = [UpdateMany({},{"$set": {"Collection": collection}})]
        result = db.get_collection(collection).bulk_write(request)

    else:
        db.get_collection(collection).drop()

Upvotes: 1

Related Questions