简体   繁体   English

Javascript - 如何解析 JSON 文件以从最近的条目中查找单个数据点

[英]Javascript - How to parse a JSON file to find a single data point from the most recent entry

I am trying to measure temperature using a sensor which is then uploaded to a mongo database.我正在尝试使用传感器测量温度,然后将其上传到 mongo 数据库。 This is then retrieved as a JSON file, accessable from visiting ('/data').然后将其作为 JSON 文件检索,可通过访问 ('/data') 访问。

I would like to firstly find the most recent entry, then find the value of the temperature from that.我想首先找到最新的条目,然后从中找到温度的值。

This is how the JSON looks (x10,000):这是 JSON 的外观(x10,000):

{
"_id": {
    "$oid": "5882d98abd966f163e36a6cf"
},
"temperature": 19,
"humidity": 30,
"epochtime": 1484970377120
}

I have set up the website using express.js, I believe I will have to somehow parse this JSON object, maybe using this to step through and find the most recent entry.我已经使用 express.js 设置了网站,我相信我将不得不以某种方式解析这个 JSON 对象,也许使用它来逐步查找并找到最新的条目。

for ("temperature" in '/data') {
    output += temperature + ': ' + obj[temperature]+'; ';
}
console.log(output[0]);

Many thanks for the assistance.非常感谢您的帮助。


UPDATE & Solution:更新和解决方案:

Many thanks to Bertrand Martel, almost perfect solution.非常感谢 Bertrand Martel,几乎完美的解决方案。

MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");

db.collection('Sensors', function(err, collection){
assert.equal(err, null);
var options = {
  "limit": 1
}
var sort = {
  "epochtime": -1
}

collection.find({}, options).sort(sort).toArray(function(err, res) {
assert.equal(err, null);

console.log("most recent temperature : " + res[0].temperature);
console.log("most recent humidity : " + res[0].humidity);
    }); 
});
db.close();
});

You can sort epochtime backward and limit the result to 1 document :您可以向后排序epochtime并将结果limit为 1 个文档:

If you use node-mongodb-native :如果您使用node-mongodb-native

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/testDB", function(err, db) {
    if (err) {
        return console.dir(err);
    }

    db.collection('test', function(err, collection) {

        collection.find({}, { "limit": 1 }).sort({ "epochtime": -1 }).toArray(function(err, res) {
            console.log("most recent temperature : " + res[0].temperature);
        });

    });
});

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

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