Q:

Create multiple collections in mongodb using PyMongo

I am trying to create multiple collections in MongoDB using pymongo module as below. But its been failing.
import pymongo
client = MongoClient('localhost:27017')
mydb = client.tstdata # connect/create a db in mongodb
list1 = ["tst-1","tst-2","tst-3"] # list of collections to be created
for each_val in list1:
    print (each_val)
    col = mydb.each_val #create collection
    col.insert_one({"name" : "test"})

Instead of creating multiple collections using values in 'each_val' variable, its just creating collection with "each_val" name; how can I fix the above error

A:

Use the syntax:
col = mydb[each_val]

The drivers do their best to (sort of) match the mongo shell. So db.x.insert will insert into collection x rather than any variable named x as you have seen.

