Get objects from database of date between yesterday and today - mongodb

I have the following schema.
const dish = new Schema({
name: {
type: string,
},
createdAt: {
type: Date,
},
)
I want to get the dishes that are created between yesterday 12AM to today's 12AM.

const dish = await Dish.aggregate([
{
$match: {
$and: [
{ createdAt: { $lt: new Date(new Date().setHours(0, 0, 0))}},
{ createdAt: { $gte: new Date(new Date().setHours(0, 0, 0) - 24 * 60 * 60 * 1000)}}
]
}
}
]);
Edited:
Here is the explanation.
new Date() give you a date like 2022-11-15T22:14:00.000+00:00 but new Date().setHours(0,0,0) will set the values to 12AM but also gives you value in millisecond like 1668449700000.
Your createdAt has value in date like 2022-11-15T22:14:00.000+00:00. Using { $lt: new Date().setHours(0, 0, 0)}} it will try to compare value between a date and a integer [2022-11-15T22:14:00.000+00:00 , 1668449700000] so you will get a wrong result.
So you need to put that into a new Date() to get the value in Date so that the $lt can compare properly. new Date(new Date().setHours(0, 0, 0))} will be equal to new Date(1668449700000) which will give you a date value and the $lt will also work properly.
As for the second condition, 24 * 60 * 60 * 1000 is 1 day in millisecond. So I've subtracted that to get the millisecond of yesterday's 12AM.

Related

why $gte and $lte do not work with a specific date like "2020/12/09" to get a documents like ISODate("2020-12-09T04:32:37.266Z")

what am I doing wrong? I am trying to filter the docs where the date matches: 2020/12/09
let date= "2020/12/09";
let startDate = new Date(new Date(date).setHours(00, 00, 00)); // output: 2020-12-09T05:00:00.000Z
let endDate = new Date(new Date(date).setHours(23, 59, 59, 999)); //output: 2020-12-10T04:59:59.999Z
let filter= {
mydate: {
$gte: startDate,
$lte: endDate,
},
};
collection:
[{ "mydate":ISODate("2020-12-09T04:32:37.266Z")}]
collection.aggregate(
[
{
$match: filter
}
]
)
no matches found
I was having the same issue. I think the issue is with the date string format.
new Date('2020/12/09') --> 2020-12-08T16:00:00.000Z
new Date('2020-12-09') --> 2020-12-09T00:00:00.000Z
I resolved the issue by changing the date string format to yyyy-mm-dd and used setUTCHours method instead of setHours since I need the UTC time,
let date = '2020-12-09'
let startDate = new Date(new Date(date).setUTCHours(0, 0, 0, 0)); --> 2020-12-09T00:00:00.000Z
let endDate = new Date(new Date(date).setUTCHours(23, 59, 59, 999)); --> 2020-12-09T23:59:59.999Z

MongoDB query based on date plus time

i've to run a query like this (sql) in MongoDb 4:
SELECT * FROM log WHERE DATE_ADD(created_at, INTERVAL 2 HOUR) < NOW()
Basically, I want to find all the documents, in the PENDING state, whose creation date PLUS TWO HOURS is less than now .. Let me explain: I want to find all the documents in the PENDING state that have been in PENDING for more than two hours.
I feel stupid, but I am failing to do this with MongoDb.
I also created a playground:
https://mongoplayground.net/p/4bifqiX2KMJ
Can you help me?
You can add hours in ISO date using $add, convert string date to ISO date using dateFromString,
let date = new Date();
db.collection.find({
status: "pending",
$expr: {
$lt: [
{
$add: [
// convert string date to ISOdate, if its already then use only "$inserted_at"
{ $dateFromString: { dateString: "$inserted_at" } },
// add milliseconds
7200000 // (60*60*2000)
]
},
date
]
}
})
Playground
Or subtract from current date and then compare the condition,
let date = new Date();
date = new Date(date.getHours()-2); //subtract 2 hours
db.collection.find({
status: "pending",
$expr: {
$lt: [
{ $dateFromString: { dateString: "$inserted_at" } },
date
]
}
})
Playground

How to find documents from date to date in MongoDB?

I would like to return results from DB, from date to date.
let resultsArray = await db.collection('scraper-results').find({
timestamp: {
$gte: Date(lastDiff),
$lt: Date(new Date())
}
}).toArray();
console.log(resultsArray);
I am using this but it returns an empty array, I tried with ISODate as well but I get the error: ISODate is not defined.
lastDiff prints : "2018-10-22T11:10:07.000Z"
Try below: (You just need to use new)
db.getCollection('scraper-results')
.find({
timestamp: {
$gte: new Date(lastDiff),
$lt: new Date()
}
});
Try like this:
timestamp: {
$gte: new Date(lastDiff),
$lt: new Date()
}
Observe the difference in output when not using new with "2018-10-22T11:10:07.000Z":
console.log(Date('2018-10-22T11:10:07.000Z'));
console.log(new Date('2018-10-22T11:10:07.000Z'));
Note that your one is incorrect so it's the equivalent of "now" (today).

MongoDB Date range query for past hour

I'm trying to write MongoDB query which will be return data from one hour ago.
There is a column time with timestamps ("time" : NumberLong("1471953787012")) and this is how it looks in SQL:
select name from table
where time between (NOW() - INTERVAL 1 HOUR) AND (NOW())
How do I write a MongoDB query to find a date range from one hour ago?
I'm trying with new Date() function but it doesn't work.
Does anyone know what I'm doing wrong?
db.coll.find({
"time" : {
$lt: new Date(),
$gte: new Date(new Date().setDate(new Date().getDate()-1))
}
})
db.entity.find({ $and:[
{
"timestamp": {
$gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
}},
{
"timestamp": {
$lte: ISODate()
}}
]})
Hope this helps...
db.coll.find({
"time": { // 60 minutes ago (from now)
$gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
}
})

Get data between two dates mongo

I need to query the data between two dates.
I was pushing data into mongo where dates are in the format : 13-10-2015 15:08:22
Is there a way to do it?
Can't i tell mongo to compare these as dates with format explicilty mentioned
You can use the generic $gte and $lte query modifiers when dealing with Dates in mongo
{ $gte: startDate, $lte: endDate }
should work just fine (where endDate and startDate are Javascript Date objects)
You can use aggregate function in mongodb.
You can get dates using this :
let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);
[Here 15 is days. It will subtract 15 days from current date].
TableName.aggregate([
{
"$match":
{
"Date":
{
"$lte": todayDate,
"$gte": beforeDate
}
}
}
])
let today = new Date();
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
{
$match: {
createdAt: {
$gte: sevenDaysAgo,
$lte: today,
},
},
},