Validate date from mongo greater than 24 hrs - mongodb

how can i validate a field form mongodb storing datetime is greater
than 24 hrs.I have to validate it is less than 24 hrs.

If you want to list all of the documents in a collection that were created 24 hours ago, then each document in the collection has to have a field representing the date it was created:
{
"title" : "A blog post",
"author" : "vmr",
"content" : "...",
"created_on" : new Date();
}
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.HOUR, -24);
Date date = c.getTime();
Then run this command to get documents which are older than 24hrs:
db.posts.find({created_on: {$lt: date}});
Hope this helps.

Related

Why spring data mongo not returning the field having time?

I have a document in my collection like
{
"_id" : ObjectId("5e3aaa7cdadc161d9c3e8014"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2134",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:30:00Z")
}
{
"_id" : ObjectId("5e3aaacddadc161d9c3e8015"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2021",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:00:00Z")
}
I am putting criteria like
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05";
String to = "2020-02-05";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.and("scheduledDepDateTime").gte(fromDate).lte(toDate);
But i am getting document only the field which have time 00 not both the document. I have two documents with that date but in response getting only one. I have tried so many things but not succeed. I want to compare only the date and ignore the time. Please help.
The from and to dates must be the lowest time and the highest time for that date, respectively; this will cover all the hours of the day.
For using the same field ("scheduledDepDateTime") with the $and operator you must use the Criteria's andOperator not the and (see AND Queries With Multiple Expressions Specifying the Same Field).
The updated code:
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05 00:00:00";
String to = "2020-02-05 23:59:59";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.andOperator(where("scheduledDepDateTime").gte(fromDate), where("scheduledDepDateTime").lte(toDate)));
// Query qry = new Query(criteria);
// List<SomeClassName> result = mongoTemplate.find(qry, SomeClassName.class, "collection_name");
The ISODate in mongod is stored as an epoch timestamp with millisecond resolution.
dateFormat.parse is likely returning ISODate("2020-02-05T00:00:00.000Z"), which would be stored in the db as 1580860800000.
This effectively means your query is {scheduledDepDateTime:{$gte: 1580860800000, $lte: 1580860800000}}, so the only possible value that could satisfy the filter is ISODate("2020-02-05T00:00:00.000Z").
To get all documents with that date, you might try making your toDate be the following day, and use $lt instead of $lte.
As suggested by #prasad todate must be the lowest time and the highest time for that date I have to set time in todate field to 23:23:59 like this and it works.
public static Date convertToDate(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}

Getting Mongo results from one month ago

I have around 30-40 records like the example before in my database and I'm looking to get the notifications that are less than 1 month old (from today's date). Is there a way in Mongo to get these results without having to pass in a today's date via JavaScript? Or if I do have to pass it in via JavaScript, how would I process this against my created date?
{
"_id" : ObjectId("48445b4dc72153e9ad7f3bfb"),
"notificationID" : "78723asd5-vnbb-xv31-afe0-fa9asf164e4",
"notification" : "Notification #1",
"created" : ISODate("2016-11-21T20:33:53.695Z")
}
Any help is appreciated, thanks.
MongoDB has its own Javascript interpreter so, unless your MongoDB server has a different date than your system, it knows the current date so you easily use simple Javascript to compute the value you're looking for using a regular Date object and use it in your query.
var d = new Date();
d.setMonth(d.getMonth() - 1); //1 month ago
db.data.find({created:{$gte:d}}); //change "data" for your collection's name
If you need a different date than your database's, I'm afraid you'll have to somehow pass it as a parameter.
const now = new Date()
const temp = new Date(now).setMonth(now.getMonth() - 6);
const priorSix = new Date(temp)
Table.find({"date" : {$gte: priorSix, $lt: new Date()}}, (err, tables) => {
if(err) throw new Error(err)
res.status(200).json(tables)
}).populate('foodList.item')
This code worked for me. It retrieves documents of the last 6 month :)

How do I fetch all mongo data which is created greater than a particular date?

I read the $gt attribute has to be used. Not able to get around this. Let's say I have some mongo data like this:
{
"startTime" : "Sun 25 Jan 2015 07:14:26 GMT",
"endTime" : "",
"jobStatus" : "JOBCANCELLED",
"uiState" : "HISTORY",
"priority" : "SILVER"
}
That's how my start time is saved in my Mongo. If I want to get the statuses of all jobs which have the start time greater than today, How do I do it?
db.getCollection('jobsCollection').find({"startTime":{$gt: "What here?"})
First you need to convert your startTime from String format to date time format.
To do from mongo shell :
db.jobsCollection.find().forEach(function(doc){doc.startTime = new Date(doc.startTime);db.jobsCollection.save(doc)});
And then you can write the query for greater than date :
db.jobsCollection.find({"startTime":{$gt: new Date("2014-02-10")});
Let me know if you face any issue.

MongoDB : Time comparison

I have a field startTime in MongoDB collection that stores time in the following form:
2015-07-22 08:19:04.652Z
I would like to find all documents that has the startTime greater than or equal to yesterday's time(from exactly one day before). I tried using the $currentDate in the find query, but I was not able to make it work.
EDITED:
Sample Document:
{
"_id" : ObjectId("55af5241e4b0ec7c53360333"),
"startTime" : ISODate("2015-08-22T08:19:04.652Z"),
"sampleId" : "SS10"
}
EDITED 2: No aggregation framework allowed.
Compute the previous date first the pass it in find query.
In javascript:
var date = new Date();
date.setDate(date.getDate() - 1);
db.col.find({'startTime':{'$gte':date}})

Remove old records in mongodb based on Month

I am trying to delete Older records present in my collection .
I have a collection named "user_track" , which consists of data in this format shown below
db.user_track.find().pretty()
{
"_id" : ObjectId("50c9afe5765fb0e4fea076ce"),
"cust_id" : "ddddd",
"symbol" : "WWWW",
"access_time" : "Thu Dec 13 2012 05:37:25 GMT-0500 (EST)"
}
{
"_id" : ObjectId("50c9afe7765fb0e4ffa076ce"),
"cust_id" : "eeeeeeeeee",
"symbol" : "WFC",
"access_time" : "Thu Dec 13 2012 05:37:27 GMT-0500 (EST)"
}
{
"_id" : ObjectId("522de3ae2191b0e41a7534dd"),
"cust_id" : "dsdsds",
"symbol" : "APPLE",
"access_time" : "Mon Sep 09 2013 11:05:18 GMT-0400 (EDT)"
}
In my collection , user_track , i want to keep only the current month's data (that is from Sep 01 2013 to current day ) and want to delete the rest of the records which doesn't belong to current month
I have tried to issue the below command , but i am not sure of how to issue this command to suit my requirement as the date i have is in different format .
db.user_track.delete( { 'access_time': {$lte: XXX} })
Please suggest .
You can give any Date with Javascript date
db.user_track.remove( { access_time : {"$lt" : new Date(year, month_0_indexed, day)} })
So for removing documents before 1 September 2013 your command should be
db.user_track.remove( { access_time : {"$lt" : new Date(2013, 8, 1) } })
September is the 9th month but the month field is zero indexed. So we make that as 8.
Mongo has a TTL feature on collections, I think this is a nice solution to such cases:
https://docs.mongodb.com/manual/tutorial/expire-data/
Basically something like:
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds:
3600 } )
In addition to other answers you may be interesting in the "Time to live” collection feature:
http://docs.mongodb.org/manual/tutorial/expire-data/
It's useful to automatically expire/remove documents from a collection after specific period of time.
Probably there is a cleaner solution but this should work:
Create new Data field from date strings:
var cursor = db.user_track.find()
while (cursor.hasNext()) {
var doc = cursor.next();
db.user_track.update(
{_id : doc._id},
{$set : {access_time_ : new Date(doc.access_time)}})
}
Now you can retrieve some records by comparing dates:
db.user_track.find({access_time_: {$lt: new Date("Sep 01 2013 00:00:00 GMT+00:00")}})
If everything works as expected remove obsolete records:
db.user_track.remove({access_time_: {$lt: new Date("Sep 01 2013 00:00:00 GMT+00:00")}})
In the future use date objects not strings
I have found a solution to address this issue .
var date=new Date();
date.setDate(date.getDate() - 1);
db.user_track.remove({"access_time":{"$lt":date}});
I will make this run automatically by putting these lines in a bash file and scheduling that script using a cron tab .
Please share your views if this is a valid solution or not ??