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

ε祈祈猫儿з 提交于 2020-06-29 05:08:13

问题


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.' });
        }
    });
};

回答1:


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



来源:https://stackoverflow.com/questions/62249133/how-to-get-data-between-the-two-dates-from-mongodb-using-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!