xeet
xeet

Reputation: 163

Dynamic index name in pymongo

I'm about to add some data to the MongoDB Atlas service and would like the indexes to be dynamic based on the source. I am currently ingesting logs from different sources (all ends up as files however) like so:

filenames = ["access_logs.log", "error.log", "stats.log"]

Currently I insert all of them to the same index: db_client.logs.insert_many(data)

I however want to use the filename (this is being passed as a variable already) as the index name. Is there a dynamic way of doing this? I can of course write case specific inserts and hardcode the name of the index based on each case but was wondering if there is another, smarter, way of doing this?

Basically i'd like to achive (please pardon the wrong syntax here, the $ is suppose to be the variable:

for filename in filenames:
  db_client.$filename.insert_many(data)

I suppose this question is more of a python specific question rather than one that is only applicable for pymongo. However, I am not sure how to phrase this specific requirement. Any help is welcome

Upvotes: 0

Views: 86

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

To use a dynamic collection name, reference it in this format:

for filename in filenames:
  db_client[filename].insert_many(data)

Upvotes: 1

Related Questions