Say that I've got a collection of users, each with a birthday in ISODate date format. eg. ISODate("1958-03-23T00:00:00.000Z"). How can I use a jongo aggregate query to get users with birthdays on the current day.This is what I have currently but it doesn't return any results even though there are users with birthdays:
Date dateOfBirth = new Date();
Integer month = new DateTime(dateOfBirth).getMonthOfYear();
Integer day = new DateTime(dateOfBirth).getDayOfMonth();
List<User> users= IteratorUtils.toList(userJongo.aggregate("
{$project:_id:1,dateOfBirth:1,name:1}}")
.and("{$match :{dateOfBirth.getDate(): {$eq: '"+day+"'}}}")
.and("{$match :{dateOfBirth.getMonth()+1: {$eq:'"+month+"'}}}")
.and("{$limit:"+limit+"}"
.as(User.class).iterator());
Thank inadvance.
How about saving user birthdays as strings and add index to that filed.
In this case your performance will increase.
And you sure dont want to use aggregation.
Just before query get current date-> format into string that you save into DB -> run db.find({birthDate: "0425(this is april 25)"})->after getting results do whatever you want.
Related
There are many similar questions asked. But not exactly similar to the issue i am facing. I have seen almost all the questions and answers around it
So the problem is
I got to insert a date field in my mongo collection
But I can't access the collection directly. I got to use a service. The service takes a string and returns me oid.
So once i construct the BasicDBObject I call toString on it and pass it on to my service.. I even tried inserting it directly in a test collection and mongo is complaining.
BasicDBObject document = new BasicDBObject();
long createdAtSinceEpoch = 0;
long expiresAtSinceEpoch = 0;
createdAtSinceEpoch = System.nanoTime();
Date createdAt = new Date(TimeUnit.NANOSECONDS.toMillis(createdAtSinceEpoch));
document.append("createdAt", createdAt);
expiresAtSinceEpoch = createdAtSinceEpoch + +TimeUnit.SECONDS.toNanos(30);
Date expiresAt = new Date(TimeUnit.NANOSECONDS.toMillis(expiresAtSinceEpoch));
document.append("expiresAt", expiresAt);
service.storeRecord(document.toString());
and the generated JSON String looks like
{
"createdAt": {
"$date": "2015-09-01T20:05:21.641Z"
},
"expiresAt": {
"$date": "2015-09-01T20:05:51.641Z"
}
and Mongo complains that
Unable to parse JSON : Date expecting integer milliseconds, at (3,17)
So If i pass milliseconds alone instead of date object in the document.append() method then it DOES NOT recognize this field as date and considers it as String but inserts into the collection
I need 2 things
1) I want the data to be inserted
2) I am planning to expire that row by adding an index to the expiresAt field. So I want mongo to recognize that its a date field
JSON makes a difference between a numeric field and a text field containing a number. The latter one is only recognized as a String; I assume that this is what you did when you thought you were giving your service the date as an integer. Unfortunately you didn’t show us the relevant code.
When I save the Date info as a non String format, I annotate the field in my DTO as below. This helps the MongoDB know that the field is to be treated as an ISO date which then would be useful for making range search etc.,
#DateTimeFormat(iso = ISO.DATE_TIME) private Date date;
Date date = new Date();
BasicDBObject date= new BasicDBObject("date", date);
Data.insert(date);
These are the basic conditions set in my code.
t1 = new JFormattedTextField(new SimpleDateFormat("dd-MM-yyyy"));
t1.setValue(new java.util.Date());
java.util.Date searchDate=(java.util.Date)t1.getValue();
Retrieving Date from the Result Set.
Date Date1 = rs.getDate("Date1");
I wanted to know whether this condition for matching the dates i enter and for retrieving the dates from database is correct or not. I am new in the world of coding.
if(new java.sql.Date(searchDate.getTime()).equals(Date1))
{
... //code
}
Nevermind...
making it...
java.sql.Date sqlSearchdate = new java.sql.Date(searchDate.getTime());
and
if(sqlSearchdate.equals(Date1)
{
...
}
solved the problem. This was so silly. My bad for asking such a question.
Yes that should work, according to http://www.mkyong.com/java/how-to-compare-dates-in-java/ though i'm not sure why you're creating a new Date object in the if statement.
I've got a table File for which I created a hibernate entity with fields:
archiveDate: Date,
createDate: Date,
copyDdate: Date,
modifiedDate: Date,
fileSourceId: Long,
fileSize: Long
I have to create a DAO for retrieving statistic data like how many files were archived in a given period of time in given intervals (daily, weekly, monthly, annually) for specified fileSourceId. Like if dao receives arguments like this:
fileSourceId = 1, startDay = '2012/01/01', endDate = '2012/02/01', interval = 'weekly'
it should return some objects like this:
{fileSourceId = 1, endDate = (end date of the first week), fileCount = 100, sizeSum = 10000 }
{fileSourceId = 1, endDate = (end date of the second week), fileCount = 120, sizeSum = 30000 }
and so on. I would like to avoid doing calculations like counting and summing on the java side as there's a couple of hundred of thousands files.
Is it possible to create a query or criteria to do this in Hibernate or it's better to do some view in database (Oracle) and query this view. I would like to avoid any oracle specific function in query because we don't want to be bound to one database (especially that we use h2 as our testing database in integration testss). How would you resolve this problem?
I am taking date of birth as input using JSON
{"dateOfBirth":"1973-08-26"}
This field exists in Person.java class
import java.util.Date;
public class Person {
Date dateOfBirth;
//Some other fields
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
}
This is mapped to person table in mysql database.
I am querying the database like:
entityId = (Long) session.selectOne("ValidatePerson", registerUserRequestParams);
Following are the entries I am making in my mapper.xml
<select id="ValidatePerson" parameterMap="ValidatePersonMap" resultType="long">
select person.entityId
from person
where
//Some other Validation checks
<if test="dateOfBirth != null">
and person.dateOfBirth = #{dateOfBirth}
</if>
);
</select>
I have a prameter Map as
<parameterMap id="ValidatePersonMap" type="java.util.HashMap">
<parameter property="dateOfBirth" javaType="java.util.Date" jdbcType="DATE" mode="IN"/>
</parameterMap>
I am not able to get any result from database.It does not select any row even though value exists.I have checked that none of other validation checks are failing. If I pass dateOfBirth as null in JSON then then I get result.
I have also written a test case and setting request as follows:
Date dob = new Date(73,7,26);
request.setDateOfBirth(dob);
When I pass values from test case as mentioned above I get result from database.
Problem occurs only when i get request parameters using json.
The format of JSOn and the format stored in DB are same
One work around I have is to manually convert java.util.Date to String in above format and pass it as string. But this is pretty bad approach and client would not like it.
Use Timestamp. Consider Joda time plug. ...and read this answer.
These three will absolutely do the magic.
Good luck!
Have you tried formatting the java date. Maybe the formats are different so it can't match between the JSON and the one stored in your db?
This worked for me:
mysql attribute type is Timestamp
and I format the date for JSON in Java like this:
Date d = new Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
String sd = sdf.format(d);
java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("HH:MM:ss");
String fakeit =sd+"T"+sdf2.format(d);
I then use fakeit
My java class (servlet) has been running fine, but recently, I noticed a problem.
In my database, I have a Date column called 'Full_Expiration_Date'. If one was entered it will store it like '2010-11-17'. If one wasn't entered, is stores it like '0000-00-00'.
In my class, I call the records from the db, and look at the 'Full_Expiration_Date' field to see if it has a date or not. If it does, I execute a few lines of code that check to see if before today's date, and if the date is NOT today's date - if both those conditions are met, the coupon has expired.
So my code works just fine when there IS an expiration date specified, but fails when '0000-00-00' is in the field.
I'm generating an array of information for each coupon in the db table. Once the checking is complete and the array is filled, its sent as a request attribute.
Here's a snippet of my code for this process -
rs = stmt.executeQuery("select Full_Expiration_Date from coupons");
//will hold value from "Full_Expiration_Date" field in db
java.sql.Date expirationDate = null;
//today's date - used for comparison
java.util.Date today = new java.util.Date();
while(rs.next()) {
//get expiration date from db for this record
expirationDate = rs.getDate(12);
if(expirationDate == null) { //should be if the field is 0000-00-00, right?
//don't do any checking against
//expiration date, this record
//doesn't have one
couponList[counter][11] = "";
} else { //10
if(expirationDate.before(today) & !today.equals(expirationDate)) {
couponList[counter][11] = "expired";
} else { //11
couponList[counter][11] = "";
}//if
}//if
counter++;
}//while
Can someone pinpoint what I'm doing wrong here? I'm certain, after testing, that it has to do with the field being 0000-00-00.
0000-00-00 is an invalid date that can't be parsed by Java. You need to allow nulls in that field so that MySQL will stop inserting 0s and that way your if(expirationDate == null) check will actually work.
This is stupid behavior IMO and you should "fix it" by turning on Strict mode. http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_no_zero_date
You can work around this using MySQL's "zeroDateTimeBehavior" configuration property. In your connection properties set:
"zeroDateTimeBehavior" to "convertToNull"
Anytime a 0000-00-00 date is retrieved, it will return null instead of throwing an exception.
Reference: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html