简体   繁体   English

Python + MongoDB,如何动态选择数据库集合

[英]Python + MongoDB, how to dynamically choose DB Collection

How can I dynamically point to a particular collection name in MongoDB with Python? 如何使用Python动态指向MongoDB中的特定集合名称?

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. 我从网络中几十个传感器中的任何一个接收数据,我想将原始数据存储到以该传感器命名的db集合中。

# 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. 除了明确地编写db.SensorName.insert_one({...}) ,我还想以某种方式引用给定的传感器/集合名称。

Thanks 谢谢

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: 给定一个数据列表,您将这样做,它将根据数据的sensorName属性将文档插入适当的集合中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM