Date Comparison in MongoDB and NodeJS

1

I would like to know how I can compare two dates in MongoDB in NodeJS, I'm using mongodb-native.

I need to compare the current date with the date that is saved to the bank, in this case the DATETIME field. To understand better in the example I put the difference that is returning to me, in the new Date ("$ DATAHORA") is taking the result of 1970-01-01T00: 00: 00.000Z that the value would be the "dateHora1" of the return. p>

I have this data in MongoDB

{
    "_id" : ObjectId("5a05db4d7ff5d05612b0165c"),
    "DATAHORA" : "2017-11-02 08:51:01",
    "INSTANCE" : "stcpappl08",
    "RESULTADO" : "1"
}
{
    "_id" : ObjectId("5a0b312be3572e39480f76e4"),
    "DATAHORA" : "2017-10-01 00:00:00",
    "INSTANCE" : "stcpappl08",
    "RESULTADO" : "1"
}

I'm passing this object array into aggregate

var consultar = [
            {
                $match: {
                    RESULTADO: "1"
                }
            },
            {
             $project: {
                 INSTANCE: 1,             
                 DATAHORA: 1,                     
                 dateDifference: { $divide: [ 
                    { $subtract: [ new Date(), new Date("$DATAHORA") ] }, 
                    1000 * 60 * 60 * 24 
                ]},
                dateHora: "$DATAHORA",
                dateHora1: new Date('$DATAHORA')
              }
             }
]

MongoDB function

db.collection("transfer").aggregate(consultar).toArray(function(err, docs) { 
     console.log(docs);                                                   
});

Return result

[                                                                                       
 {                                                                                                 
   _id: 5a05db307ff5d05612b0165b,
   DATAHORA: '2017-11-10 06:00:00',
   INSTANCE: 'stcpappl02',
   dateDifference: 17485.732020763888,
   dateHora: '2017-11-10 06:00:00',
   dateHora1: 1970-01-01T00:00:00.000Z                                    
 }                                                                          
]
    
asked by anonymous 15.11.2017 / 18:38

1 answer

0

The format of the question is correct, the problem was how the date was being saved.

It was being saved in String and not in Date, so I could not subtract the dates.

    
16.11.2017 / 19:25