MongoDB Date range query for past hour - mongodb

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)
}
})

Related

Get objects from database of date between yesterday and today

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.

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 retrieve documents with createdAt more than 48 hours in mongoose

I need to retrieve documents where the createdAt timestamp is more than 48 hours in mongoose.
Here's my sample code below but it doesn't retrieve any documents even though there're documents that match the condition.
Model.find({
createdAt: { $lt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) },
});
NB: The createdAt field is the default in mongoose when timestamp is enabled { timestamps: true }
I would really appreciate it if anyone can help out, thanks in advance.
Try
var days= 2;
var date = new Date(date.setDate(date.getDate() - days));
Model.find({createdAt : {$lt : date}}).count());
With MongoDB aggegation framework, we have access $$NOW (Standalone) | $$CLUSTER_TIME (Cluster) variable which returns current date.
If we subtract 172800000 miliseconds (48 hours) from current date and use $expr operator, we can get desired result.
Try this one:
Model.aggregate([
{
$match: {
$expr: {
$gte: [
"$createdAt",
{
$toDate: {
$subtract: [
{
$toLong: "$$CLUSTER_TIME"
},
172800000 // 2 x 24 x 60 x 60 x 1000
]
}
}
]
}
}
}
]).exec();
MongoPlayground
Thanks to everyone that tried to help out.
My solution above works, I wasn't getting any records at that time cos unknowing to me my env file was pointing to another MongoDB server.

Issues aggregating mongo records by the last 7 days

I'm trying to count the occurences from each id_atendentes on the last 7 days/week.
I have the following query:
db.atendimentos.aggregate([
{'$group' :
{'_id' :
{'id_atendente':'$id_atendente', 'date':
{ '$gte': new Date((new Date().getTime() - (7 * 24 * 60 * 60 * 1000))) }
}},
'sum': {'$sum': 1} }
])
I thought that it would work, but it didn't.
I'm aware of the $week operator but I don't think that it does what I want to do.
I've got the following error: A pipeline stage specification object must contain exactly one field.
I guess that it may be something with my 'date': { '$gte' }... part.
Hope to get some help, thanks!
So if I understand right, you would like to get last week documents, and then group them by the id_atendente, and count the amount each atendente occurred during the last week.
If that is the case, you first need to filter out documents from the last week with a $match stage, and then follow it with a $group stage to group by the atendente id.
I think the following code will do the job:
db.atendimentos.aggregate([
{
'$match': {
'date': {'$gte': new Date((new Date().getTime() - (7 * 24 * 60 * 60 * 1000)))}
},
},
{
'$group':
{
'_id': "$id_atendente",
'sum': {'$sum': 1}
},
}
])

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,
},
},
},