如何使用 Node-RED 从 MongoDB 中提取值?

How to extract value from MongoDB using Node-RED?

我想使用 Node-REDMongoDB 中提取值。在下面提到的流程中,RFID Reader 运行 of Raspberry Pi 读取 RFID(ex:"badgeID": 12) 并使用 MQTT 生成值,在 Node-RED 中订阅相同的值,并将此订阅值传递给 Node-RED 中的 MongoDB node order 根据这个 badgeID 过滤值。在 MongoDB 数据库中,一个文档的结构类似于

{ "_id": "5631a6ba7de98c4a497dfdcb", "badgeID": "1", "tempValue": 25,
"unitofMeasurement": "C" }

。为此,我在 Node-RED 中的流程如下:

[{"id":"3015a0de.cfea6","type":"mongodb","z":"6ab069e2.954f98","hostname":"127.0.0.1",
"port":"27017","db":"iotsuiteuser","name":"ProfileDB"},{"id":"5a6e14aa.a591ec","type":"mqtt-
broker","z":"6ab069e2.954f98","broker":"test.mosquitto.org","port":"1883","clientid":"",
"usetls":false,"verifyservercert":true,"compatmode":true,"keepalive":"15","cleansession":true,
"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","birthTopic":"","birthQos
":"0","birthRetain":"false","birthPayload":""},{"id":"2ec6f370.d1390c","type":"mqtt in","z":"6ab069e2.954f98","name":"RFID Reader Subscriber","topic":"badgeDetected","broker":"5a6e14aa.a591ec","x":137,"y":151,"wires":[["fc22a30d.03dd6"]]},{"id":"fc22a30d.03dd6","type":"function","z":
"6ab069e2.954f98","name":"Proximity","func":"sensorMeasurement=JSON.parse(msg.payload);\nmsg.payload=sensorMeasurement.badgeID;
\nreturn msg;\n","outputs":1,"noerr":0,"x":365,"y":188,"wires":[["48d08989.b72f78"]]},{"id":
"bb7c3bfd.4483c8","type":"debug","z":"6ab069e2.954f98","name":"Debug","active":true,"console":
"false","complete":"payload[0].tempValue","x":930,"y":221,"wires":[]},{"id":
"48d08989.b72f78","type":"mongodb in","z":"6ab069e2.954f98","mongodb":"3015a0de.cfea6","name":"ProfileDB","collection":"ProfileDB","operation":"find","x":613,"y":191,"wires":[["bb7c3bfd.4483c8"]]}]

Node-RED调试控制台输出显示如下:

[ { "_id": "5631a6ba7de98c4a497dfdcb", "badgeID": "1", "tempValue": 25,
"unitofMeasurement": "C" }, { "_id": "5631a6cd7de98c4a497dfdcc", "badgeID": "2", 
 "tempValue": 28, "unitofMeasurement": "C" }, { "_id": "5631b84023f7c97bc1044178", "badgeID": "3", "tempValue": 31, "unitofMeasurement": "c" }, { "_id": "565175ded239daf9794b1d48", "badgeID":
"4", "tempValue": 24, "unitOfMeasurement": "C" }, { "_id": "567287cc5e18a39f297395d6", 
"badgeID": "69d65035", "tempValue": 33, "unitofMeasurement": "C" } ]

我想 select tempValue where badgeID="69d65035"。这里的问题是它显示给定集合中的所有文档。这该怎么做 ?我走错路了吗? MongoDB数据库中的文档片段如下:

您的功能节点包含以下内容:

sensorMeasurement=JSON.parse(msg.payload);
msg.payload=sensorMeasurement.badgeID;
return msg;

这将只发送 "69d65030" 到 mongo 节点,它不知道要将其与文档中的哪个字段匹配。

Mongo 查找文档说您需要传递和对象以用于过滤器,因此要匹配 badgeID,您需要有效负载看起来像这样:

{ badgeID: '69d65030'}

为此,函数应如下所示:

sensorMeasurement=JSON.parse(msg.payload);
msg.payload={ badgeID: sensorMeasurement.badgeID};
return msg;

终于找到答案了。 Proximity节点逻辑如下:

sensorMeasurement=JSON.parse(msg.payload);
msg.payload={ badgeID: sensorMeasurement.badgeID};
msg.projection = {'_id' : 0,'tempValue':1};
return msg;

以上代码仅从数据库中获取 tempValue。