I am trying to find all rows before a certain date using mongoTemplate in Spring Java. This is returning no rows though there are lots of old records.
What is the problem?
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, -73);
Date prevDate = cal.getTime();
List<AuditTrailDTO> dt = mongoTemplate.find(Query.query(Criteria.where("AUDIT_CREATE_DATETIME").lte(prevDate)), AuditTrailDTO.class);
AUDIT_CREATE_DATETIME in Mongo DB is stored in this format:
Audit_Create_DateTime:2019-07-10 08:47:02.078
It should work if the type of Audit_Create_DateTime is Date, so I assume Audit_Create_DateTime is of String type.
You can do the following to do a less-than-equals logic on a String field;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Query query = Query.query(Criteria.where("AUDIT_CREATE_DATETIME").lte(dateFormat.format(prevDate)));
List<AuditTrailDTO> dt = mongoTemplate.find(query, Customer.class);
which will return proper results, though I recommend properly storing Date values as correct type rather than in String type.
Related
I am trying to retrieve records from mongodb collection after certain date but the date field is stored as a string in mongodb collection. The below query doesn't work well I guess because it does a string comparison. How can I convert the string date from mongo and then compare with input date.
`mongoOperations.find(query(where("lastUpdated").gte(inputTimeStamp).and("status").in("COMPLETED")), Cart.class);`
Something like this worked for me. This may not be the best way to do it because it has potential of sql injection but I made sure data is sanitized before it reaches here.
String queryStr = "{\"$expr\": {\"$gte\": [{ \"$dateFromString\": { \"dateString\": \"$lastUpdated\",timezone:\"America/New_York\" }}, new Date(\"%s\") ]},status:{$in:[\"COMPLETED\"]}}";
BasicQuery query = new BasicQuery(String.format(queryStr,timeStamp));
return mongoTemplate.find(query, Cart.class);
MongoCollection<Document> Person_List = db.getCollection("Person");
MongoCollection<Document> active_list = db.getCollection("activelist");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
String todaydate = format.format(new Date());
ArrayList<Document>
activeList=Person_List.find(Filters.regex("LastUpdate",todayDate.toString())).into(new
ArrayList<Document>());
This is the code what we have written, here we need to fetch the month from todaydate and need to compare with month of LastUpdate field, how to fetch the month from LastUpdate document field in mongo db, LastUpdate is the date string, can someone please help me.
Query to fetch records for time range of 10 seconds is fetched properly in mongo shell using below:
db.getCollection('collection-name').find({"#timestamp":{"$gte": ISODate("2018-02-07T01:51:45.005Z"),"$lt": ISODate("2018-02-07T01:51:55.005Z")}});
But in spring-data-mongodb I am unable to get the data using below methods. Either I am not able to define ISODate("String value") or new Date("String value") in #Query annotation or mongo query criteria.
Method 1: Mongo Repository & Query
#Query("{'#timestamp' :{'$gte':?0, '$lt':?1}}")
public List<collection-name> findByTimestamp( Date date,Date newdate);
Method 2: Using Mongo Query with criteria
Query query = new Query();
query.addCriteria(Criteria.where("#timestamp").gte( date).lt(newdate));
where date and new date fields are:
DateFormat df=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS\'Z\'");
Date date = df.parse("2018-02-07T01:51:45.005Z");
Date newdate = df.parse("2018-02-07T01:51:55.005Z");
I'm trying to build a query for all orders which were created today.
My Order-Entity has a datetime field like this:
#Column(name = "OrderCreationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date orderCreationDate;
Named-Query:
#NamedQuery(name = "OrderHeader.findByOrderCreationDate", query = "SELECT o FROM OrderHeader o WHERE o.orderCreationDate = :orderCreationDate")
I tried to build the query like this:
public List<OrderHeader> findFromToday() {
Date dateToday = new Date();
TypedQuery<OrderHeader> query = em.createNamedQuery("OrderHeader.findByOrderCreationDate", OrderHeader.class).setParameter("orderCreationDate", dateToday);
return query.getResultList();
}
Of course the ResultList is empty since the date AND time would have to match.
Unfortunately I need the time in my database, so the orderCreationDate needs to stay datetime/timestamp.
So how can I query for a specific date, ignoring the time?
thanks!
Your call to setParameter needs to pass in the temporal type argument also, defining what to use for comparison.
http://www.datanucleus.org/javadocs/javax.persistence/2.1/javax/persistence/Query.html#setParameter-java.lang.String-java.util.Date-javax.persistence.TemporalType-
I have date in new Date() format. I need to convert to SQLite date time format.(2014-01-05T00:00:00.000Z). Is it possible to do so??
var date = new Date();
now I need to convert this date to SQLite datetime format like (2014-01-05T00:00:00.000Z).
Try:
var date = new Date();
var sqllite_date = date.toISOString();
Use this
// Create an instance of the Date class
var date = new Date();
// Convert it to an ISO string
var sqliteDate = Date.toISOString();
take a look at this W3schools
You can use strftime, from date and time functions.
SELECT strftime('%d-%m-%Y', 'now')
Output
10-06-2010
Hope this helps ..:)