Fetch month from data field in mongo db document - mongodb

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.

Related

Firestore timestamp the same day condition

I have the table with timestamp. I want to check timestamp with the same day date. If date is 21/06/2020, I want to get the same day records. That code does not work:
where("creation_date", "==", new Date())
I figured it out. Here is the code:
const startToday = new Date(),
endToday = new Date();
// Set up start date
startToday.setHours(0);
startToday.setMinutes(0);
startToday.setSeconds(0);
// Set up end date
endToday.setHours(23);
endToday.setMinutes(59);
endToday.setSeconds(59);
.where("creation_date", ">=", startToday)
.where("creation_date", "<=", endToday)

Querying mongoTemplate using date

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.

:Spring data is able to fetch data between 2 dates but not same date different times of same date

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");

JPA-Query for a Date in a Datetime column

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-

Matching mongo query using Java

Hi I want to query MONGO using java.
I have a query like below:
db.flights.find({"timestamp" : {"$lte": new Date("2014-09-05T00:00:00.001Z")}}).count()
Which gives output as 68
When I try to get using java code like below:
table = db.getCollection("flights");
DBObject match = new BasicDBObject();
Date endDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2014-09-05T00:00:00.001Z");
match.put("timestamp", new BasicDBObject("$lte", endDate));
int count=table.find(match).count();
System.out.println(collections+" "+"COUNT : "+count);
The output is 48.
Can anybody tell me the issue in code ??
saving format
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
className classObject=null;
Date d1=new Date();
classObject.setDateColumn(format.parse(format.format(d1)));
/---------------------------------------------------/
checking format
Date d1=new Date();
Date startDate=format.parse((formatDate.format(d1)+" 00:00:00"));
Date endDate=format.parse((formatDate.format(d1)+" 23:59:59"));
classObject=classNameService.classObjectCount(startDate,endDate);
/---------------------------------------------------/
service method
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
#Autowired(required=true)
private MongoTemplate mongoTemplate;
className classObject=null;
Query query = new Query();
query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testId").in(testId));
query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testDate").gte(startDate).lte(endDate));
List<className> classNames=mongoTemplate.find(query, className.class);//put your class name..className
if(classNames.size()>0)
classObject=classNames.get(0);