Search code examples
pythonmongodbreflectioncollectionsintrospection

Python + MongoDB, how to dynamically choose DB Collection


How can I dynamically point to a particular collection name in MongoDB with Python?

I receive data from any 1 of a few dozen sensors in my network, and I want to store the raw data into a db collection named for the sensor.

# Server Parameters
host = '1.2.3.4'
port = 27017
client = MongoClient(host, port)
db = client.myDB                # use database myDB

# receive data from sensors
# {"sensorName":"...", "x":"...", "y":"...", "z":"...", "time":"..."}

db.SensorA.insert_one({...})    # record raw data in the collection for SensorA
db.SensorB.insert_one({...})
db.SensorC.insert_one({...})

Instead of explicitly writing db.SensorName.insert_one({...}), I'd like to somehow reference the given sensor/collection name.

Thanks


Solution

  • you can reference the collection names using this syntax too:

        db["SensorA"].insert_one({...})
    

    you would do it like this given a list of data this will insert the documents in the proper collection based on the sensorName attribute of the data:

        for data in data_list:
            db[data["sensorName"]].insert_one({...})