Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm.io Query with GroupBy

I want to group some accounts by month, can i do this with Realm.io?

public class Account extends RealmObject {
.....
 private Date date;
}

RealmResults accounts = realm.where(Account.class)
.beginGroup()
.equalTo("date", "MONTH(date)")//<----- wrong code
.endGroup()
.findAll();

thanks

like image 929
schwertfisch Avatar asked May 25 '15 04:05

schwertfisch


1 Answers

Realm doesn't support GroupBy yet. Also be aware that beginGroup() is actually the same as parentheses. So your query is actually interpreted as :

// SQL pseudo code
SELECT * FROM Account WHERE (date = MONTH(date))

In Realm you would have to do something like this to select a single month:

// Between is [ monthStart, monthEnd ] 
Date monthStart = new GregorianCalendar(2015, 5, 1).getTime();
Date monthEnd = new GregorianCalendar(2015, 6, 1).getTime() - 1;
accounts = realm.where(Account.class).between("date", monthStart, monthEnd).findAll();

or something like this to detect when a month changes

// pseudo code. You might want to use Calendar instead
accounts = realm.where(Account.class).findAllSorted("date")
Iterator<Account> it = accounts.iterator();
int previousMonth = it.next().getDate().getMonth();
while (it.hasNext) {
  int month = it.next().getDate().getMonth();
  if (month != previousMonth) {
    // month changed
  }
  previousMonth = month;
}
like image 128
Christian Melchior Avatar answered Oct 26 '22 15:10

Christian Melchior