nathanaelx
nathanaelx

Reputation: 13

NodeJS + MongoDB: Show entries after specific date

I have a simple API call to mongoDB that shows me all the entries, it works perfectly and looks like this:

   MongoClient.connect(url, function(err, db) {
            if (err) return res.json("Error:Database Connection error" );   
            var dbo = db.db("radar");
            var query = {   };
                dbo.collection("changes").find(query).toArray(function(err, result) {
                    if (err) return res.json("Error:Database error" );   
                    res.json( result );   
                    db.close();

After googling, I can't seem to find a query to only show entries after a specific date, or even todays date. Can anybody assist?

JUST FYI, data:

 data = {
         "change_number": "CRQ91320s23",
         "change_description": "Nexus work",
         "date": "2/10/2020",
         "changeowner" : "Jeffre Hocking",
         "implementer" : "nathan",}

Upvotes: 0

Views: 87

Answers (1)

eol
eol

Reputation: 24565

Since your date-field is of type String you will need to convert it to a Date in order to be able to correctly compare it to other date values. You can do something like this to find all dates > 2020-10-01 :

db.collection('changes').aggregate(
    [{
            $addFields: {
                actualDate: {
                    $dateFromString: {
                        dateString: '$date',
                        format: "%d/%m/%Y"
                    }
                }
            }
        }, {
            $match: {
                actualDate: {
                    $gt: new Date("2020-10-01T00:00:00.000Z")
                }
            }    
        }
    ])

It would simplify things if you'd define date as an actual Date instead of a String though.

Upvotes: 1

Related Questions