簡體   English   中英

Javascript - 如何解析 JSON 文件以從最近的條目中查找單個數據點

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

我正在嘗試使用傳感器測量溫度,然后將其上傳到 mongo 數據庫。 然后將其作為 JSON 文件檢索,可通過訪問 ('/data') 訪問。

我想首先找到最新的條目,然后從中找到溫度的值。

這是 JSON 的外觀(x10,000):

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

我已經使用 express.js 設置了網站,我相信我將不得不以某種方式解析這個 JSON 對象,也許使用它來逐步查找並找到最新的條目。

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

非常感謝您的幫助。


更新和解決方案:

非常感謝 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();
});

您可以向后排序epochtime並將結果limit為 1 個文檔:

如果您使用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