Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 411
Ryan Loggerythm Avatar asked Jun 09 '26 08:06

Ryan Loggerythm


1 Answers

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({...})
like image 134
H. Trizi Avatar answered Jun 11 '26 21:06

H. Trizi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!