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),
},
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},
}
},
])
{
"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/
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 BSONdate
type. See Date for more information.