简体   繁体   English

使用时间戳节点js从mongodb获取今天导入的数据

[英]get today's imported data from mongodb using timestamp node js

I add reports into a MongoDB database by current timestamp but I am not able to retrieve today's imported data because the current timestamp is different from the timestamp's value of inserted data.我按当前时间戳将报告添加到 MongoDB 数据库中,但我无法检索今天导入的数据,因为当前时间戳与插入数据的时间戳值不同。 how can I see data by using timestamp?如何使用时间戳查看数据?

add reprots添加报告


reportsController.addReports = function (req, resp) {


    let battriesObjs = [];
    let banksObjs = [];
    let reports = req.body;

    // console.log(batteries);


    const siteReports = new SiteReports({
        siteId: reports.siteId,
        environmentParam1: reports.envp1,
        environmentParam2: reports.envp2,
        environmentParam3: reports.envp3,
        reportDate: moment().valueOf()
    });


    let btr = reports['battries'];
    btr.forEach(function (btry) {
        const batteryReports = new BatteryReports({
            batteryId: btry.bid,
            batteryStatus: btry.status,
            batteryVoltage: btry.voltage,
            batteryTemperature: btry.temperature,
            reportDate: moment().valueOf()
        });

        battriesObjs.push(batteryReports);
    });


    siteReports
        .save()
        .then(value => {
            console.log("insert sampleCollection result ", value);
            BatteryReports
                .insertMany(battriesObjs)
                .then(valueBatteries =>
                    resp.status(status.OK)
                        .json({'respond': 'the document is updated successfully'}))
                .catch(err => {
                    console.log("bulk insert sampleCollection error ", err);

                });

        })
        .catch(err => {
            console.log("bulk insert sampleCollection error ", err);
        });


};



get reprots得到回报


reportsController.getAllTodayBatteryReports = function (req, resp) {

    console.log(req.query.batteryBankId, moment().valueOf());
    BatteryReports.aggregate([
        {
            $match: {

                "reportDate": moment().valueOf().toString()
            }
        }
        ,
        {
            $lookup:
                {
                    from: "batteryschemas",
                    localField: "batteryId",
                    foreignField: "batteryId",
                    as: "batteryReports_with_their_info"
                }
        }
        ,
        {
            $match:
                {"batteryReports_with_their_info.batteryBankId": new mongoose.Types.ObjectId(req.query.batteryBankId)}

        }
        ,
        {
            $replaceRoot: {newRoot: {$mergeObjects: [{$arrayElemAt: ["$batteryReports_with_their_info", 0]}, "$$ROOT"]}}
        }
        ,
        {
            $project: {
                batteryReports_with_their_info: 0,
                batteryBrand: 0,
                batteryMaximumChargingCurrent: 0,
                batteryCycleOfCharge: 0,
                batteryModel: 0,
                batteryProductDate: 0,
                batteryInternalResistance: 0,
                batteryCapacity: 0,
                __v: 0
            }
        }


    ], function (err, result) {
        console.log(result);
        if (err) {
            resp.status(status.NOT_FOUND).json({'respond': err + ''});
        } else {

            resp.status(status.OK).json(result);
        }
        // console.log(result);
    });
};



As you see this part of my code get the current timestamp and put it to the MongoDB match method but although some data were added in today's timestamp, I cannot get these records by current timestamp value.如您所见,我的这部分代码获取当前时间戳并将其放入 MongoDB 匹配方法,但尽管在今天的时间戳中添加了一些数据,但我无法通过当前时间戳值获取这些记录。

$match: {
              "reportDate": moment().valueOf().toString()
        }

samples样品

 {
        "_id": "5d3c9116ee51fe32b44160f6",
        "batteryId": "1",
        "batteryVoltage": "5.5",
        "batteryVoltageMin": "34",
        "batteryVoltageMax": "34",
        "batteryMinTemperature": "443",
        "batteryMaxTemperature": "43",
        "batteryBankId": "5d29c1469e0e8b3afcf3a1e6",
        "batteryStatus": "H",
        "batteryTemperature": "38",
        "reportDate": "1564250390757"
    }

You can assign moment().valueOf() value to an object and use it against reportDate.您可以将moment().valueOf()值分配给对象并将其用于 reportDate。 Plus moment().valueOf() will give you timestamp in milliseconds then inserted time will be different to querying time, So you need to do a range query in order to get specific records/documents or else pass exact timestamp to get exact match.加上moment().valueOf()将以毫秒为单位为您提供时间戳,然后插入的时间将与查询时间不同,因此您需要进行范围查询以获得特定的记录/文档,或者传递精确的时间戳以获得精确匹配。

let's say you've inserted few documents today, and wanted to run your query at a given timestamp on the same day(be mindful of timestamps are of same zone) then,假设您今天插入了几个文档,并希望在同一天在给定的时间戳运行您的查询(请注意时间戳属于同一区域)然后,

let currentTimeStamp = moment().valueOf().toString()
let startOfDayTimeStamp = moment().startOf('day').valueOf().toString()

then,然后,

$match: {
              "reportDate": { $gt: startOfDayTimeStamp, $lt: currentTimeStamp }
        }

If you're dealing with collection which has frequent writes, then you're dealing with high amounts of data for read query like this, just keep in mind to do proper indexing.如果您正在处理频繁写入的集合,那么您正在处理像这样的读取查询的大量数据,请记住进行适当的索引。

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

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