Home:ALL Converter>Create multiple collections in mongodb using PyMongo

Create multiple collections in mongodb using PyMongo

Ask Time:2020-01-13T15:14:26         Author:bala v

Json Formatter

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

Author:bala v,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59712032/create-multiple-collections-in-mongodb-using-pymongo
Belly Buster :

Use the syntax:\n\ncol = mydb[each_val]\n\n\nThe 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.",
2020-01-13T09:10:47
yy