0

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.

Winnie
  • 89
  • 2
  • 9
  • I don't know `DateTime` (I assume it's not the static inner class of `Formatter`) but did you check the value of `month`? Note that `Date.getMonth()` will return a 0-based number, i.e. for August it would return 7 instead of 8 and if `month` is 8 you won't get a match. – Thomas Aug 03 '16 at 10:29
  • Yes @Thomas that's why I've added `+1` – Winnie Aug 03 '16 at 10:32
  • I don't know jongo, but in general you do not need an aggregation for this kind of query - what you describe is a simple find() with a single condition. – mtj Aug 03 '16 at 10:40
  • hello @mtj, thanks. I had a simple find, however that took a while to return a response as users collection got larger and quite a number of them had birthdays, even though I've indexed the dateOfBirth field. – Winnie Aug 03 '16 at 10:47

1 Answers1

0

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.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24