Search code examples
javascriptindexeddbdexie

get GroupBy count in Dexie


I have an IndexedDB table that follows accepts following structured JSON as a row:

{
    id : 1,
    name : 'doc1',
    createdDate : '2018-08-08'
}

I want to get count for each available date in the table. ie: groupby:date then count. Expected example output is in the format of:

{
    '2018-08-08' : 5,
    '2018-08-18' : 19,
    ...
}

Table contains large number of records. So, how can efficiently achieve this requirement using Dexie?


Solution

  • If you index createdDate,

    const db = new Dexie("yourDB");
    db.version(1).stores({
      yourTable: "id, name, createdDate"
    });
    

    Then you could do the following:

    const result = {}
    await db.yourTable.orderBy('createdDate').eachKey(date => {
      result[date] = (result[date] || 0) + 1;
    });