realm-cpp icon indicating copy to clipboard operation
realm-cpp copied to clipboard

How to get Aggregate and Stats on a given column in a collection?

Open vtharmalingam opened this issue 11 months ago • 3 comments

Hi Greetings!

Here is the struct of my collection:

    struct commission_ledger {
        realm::primary_key<realm::object_id> _id;
        int64_t ts;
        int64_t ticket;
        double amount;
    };
    REALM_SCHEMA(commission_ledger, _id, ts, ticket, account)

I need to find the last timestamp when the commission was processed. Currently, I use this kind of code, but I think it is inefficient.

	auto recs = realm_instance->objects<commission_ledger>();

	int64_t ts = 0;
	for (auto& rec : recs) {
		if (rec.ts > ts)
			ts = rec.ts;
	}

Is there a direct "aggregate" syntax possible to be used here and in similar other cases?

Thanks, Tharma

vtharmalingam avatar Feb 27 '24 09:02 vtharmalingam

➤ PM Bot commented:

Jira ticket: RCPP-51

sync-by-unito[bot] avatar Feb 27 '24 10:02 sync-by-unito[bot]

You could do realm_instance->objects<commission_ledger>().sort("ts", false) and use the first element of the result.

kneth avatar Mar 06 '24 11:03 kneth

Wonderful, thank you very much! This assistance is truly invaluable. Could you provide any guidance on where I might find documentation covering concepts like "groupby" and others similar to "sort"? Thanks, in advance!

vtharmalingam avatar Mar 06 '24 11:03 vtharmalingam