简体   繁体   中英

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. 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.

$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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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