Mongo converting timestamp to date

2k views Asked by At

Im still new in mongo but i have a data in mongo collection that is structured like this :

{
    "_id" : ObjectId("5f79931104a8f102f761398e"),
    "data1" : "This is a data",
    "data2" : "This is a data",
    "timeStampVar" : Timestamp(1603377200, 0),
},

Currently i am trying to grab data in the last 14 Days using the timeStampVar. So far my code are like this:
var yesterdayStart = new Date();
yesterdayStart.setDate(yesterdayStart.getDate() - 14);
yesterdayStart.setUTCHours(0,0,0,0);


var yesterdayEnd = new Date();
yesterdayEnd.setDate(yesterdayEnd.getDate() - 1);
yesterdayEnd.setUTCHours(23,59,59,999);

db.collection_name.aggregate([{ 
    "$addFields": {
      "date": {"$toDate": "$timeStampVar"}
    }
  },

  { 
    "$match": {
        "date": { $gte: yesterdayStart, $lte: yesterdayEnd},
      }
  },

])

I'm encountering issue when trying to use the $toDate to convert my 10-digit timestamp into a date object. As it says this :
{
    "message" : "Unsupported conversion from timestamp to date in $convert with no onError value",
    "ok" : 0,
    "code" : 241,
    "codeName" : "ConversionFailure",
    "name" : "MongoError"
}

Am i missing something here?. On the mongo documentation of $toDate i see that the examples are using 13-digit timestamp could it be that it does not support a 10-digit timestamp?
https://docs.mongodb.com/manual/reference/operator/aggregation/toDate/



Thanks in advance
1

There are 1 answers

2
Wernfried Domscheit On BEST ANSWER

Whenever one has to work with Date/Time values in javascript then I recommend Moments.js library. It makes your life much easier.

Would be like this:

{ 
 "$match": {
    "date": { 
       $gte: moment().subtract(14,'days'),startOf('day').toDate(),
       $lte: moment().subtract(1,'days'),endOf('day').toDate(),
    },
  }
}

Have a look at Timestamps:

Note

The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.