Get data between two dates mongo - mongodb

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

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.

Query to get data from mongodb using ObjectId ("xxxxxxxxx").GetTimestamp()

I am starting in the world of mongodb.
I have the following question:
I want to find the items that were posted from date x. In the records I have no date but I can get it from this statement:
ObjectId ("5ffdc390fdd1596ca5870bec"). GetTimestamp ()
whose result is: ISODate ("2021-01-12T15: 43: 12Z")
How could I create a query that returns all the records that were created from a given date, for example from 2021-01-12?
Thank you very much.!
The mongo Shell is an interactive JavaScript interface to MongoDB, so the solution by Leftium should work.
function objectIdWithTimestamp(timestamp) {
/* Convert string date to Date object (otherwise assume timestamp is a date) */
if (typeof(timestamp) == 'string') {
timestamp = new Date(timestamp);
}
/* Convert date object to hex seconds since Unix epoch */
var hexSeconds = Math.floor(timestamp/1000).toString(16);
/* Create an ObjectId with that hex timestamp */
var constructedObjectId = new ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
/* Find all documents created between Jan 12th, 2021 and Jan 13th, 2021 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('2021/01/12'), $lt: objectIdWithTimestamp('2021/01/13') } });
You can query it directly:
db.collection.find({
$expr: {
$gte: [ {$toDate: "$_id"}, ISODate("2021-01-01T00:00:00Z") ] }
}
)
Usually I prefer the moment.js library, could be this for example:
db.collection.find({
$expr: {
$gte: [ {$toDate: "$_id"}, moment().startOf('day').subtract(3, 'days').toDate() ] }
}
)

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