简体   繁体   中英

How to get data between the two dates from mongodb using mongoose

My question is simple.Tried to get record from mongodb between the two dates like[ 01-06-2020 to 07-06-2020].But not working.How to do it?

Date format is dd-mm-yyyy

mongodb records:

[
{ 
_id:ObjectId("5edd1df67b272e2d4cf36f70"),
 date:"01-06-2020", 
 pid:1,
 pname:"Micheck" 
},
{ 
_id:ObjectId("5edd1dk67b272e2d4cf31f72"),
 date:"03-06-2020", 
 pid:2,
 pname:"Zohn" 
},
{ 
_id:ObjectId("5edd1rf67b272e2d4cf16f73"),
 date:"07-06-2020", 
 pid:3,
 pname:"Robert" 
},
{ 
_id:ObjectId("5edd1dw67b272e2d4cf76f76"),
 date:"01-05-2020", 
 pid:6,
 pname:"Josebh" 
}
]

data.controller.js:

module.exports.getReportTableData = (req, res, next) => {
    let collectionname = req.query.collection; 

    let date1 = "01-06-2020"; //dd-mm-yyyy
    let date2 = "07-06-2020"; //dd-mm-yyyy

    let tableReportdata = dbc.model(collectionname);
    tableReportdata.find({ date: date1,date2 }, function(err, docs) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log("Successful loaded data");
            res.json({ data: docs, success: true, msg: 'Data loaded.' });
        }
    });
};

This solution Needs Mongo server version > 4.0.0

According to OPs comment he's using version 4.2.7

Mongo is currently treating your fields as a string, and not a date, so first you'll have to convert them to dates.

I would recommend changing your field type to date while writing to the DB, or adding a new field with date type for better performance and less overhead

To do this conversion at runtime, you'll have to use the aggregation pipeline with the, addFields dateFromString match gte and lte operators.

Your code should look like:

let date1 = new Date("2020-06-01T00:00:00.000Z"); // date objects
let date2 = new Date("2020-06-07T00:00:00.000Z");

let tableReportdata = dbc.model(collectionname);
tableReportdata.aggregate([{
        $addFields: {
            convertedDate: {
                $dateFromString: {
                    dateString: "$date",
                    format: "%d-%m-%Y",
                    timezone: "UTC"
                }
            }
        }
    },
    {
        $match: {
            convertedDate: {
                $gte: date1,
                $lte: date2,

            }
        }
    }
], function(err, docs) {
    if (err) {
        console.log(err);
        return;
    } else {
        console.log("Successful loaded data");
        res.json({
            data: docs,
            success: true,
            msg: 'Data loaded.'
        });
    }
});

Playground Link

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