Map reduce to group by

Looking for good examples on map reduce to get the group by result on specific key in Couchbase Lite iOS

Can you be more specific about what you’re looking for?

I have document with a keys Key1, Key2…Key5. There will be duplicate records with Key1. I need to show all the unique records of Key1 along with Key2…Key5 in a list order by Key5

I tried groupLevel as below

output of my mapBlock is emit([key1, key2], doc) and query.groupLevel = 1 but I was not able to get any other details of the document other than key1. Am I missing anything ??

If you set groupLevel=1 you will get one-item keys in the result. All the things that are different in the grouped keys are not included in the output.

For what you’re doing it sounds like you’ll need to iterate over all the rows without grouping and collect the values that you need.

Okay, but in some cases records are in lakhs and it is taking time to iterate over all rows :frowning: Is there any approach other than iterating over all rows in the result??

What’s “lakhs”?

I’m not exactly sure what your requirements are; can you explain in more detail? It just sounds like you need to group by Key1 but you still need to collect aggregate info about the rows that are being grouped?

Records are in “lakhs” which needs to be grouped by Key1. I was expecting the whole document information for each row after grouping.

As per documentation of CBLQueryRow, it will not return document information when grouping was used. I want to check if there is any alternative way to get the document information when grouping is used.

/* This will be nil if a grouping was enabled in the query, because then the result rows don’t correspond to individual documents. */
open var document: CBLDocument? { get }

Grouping works similarly to SQL GROUP BY — it’s for aggregation. If you want to look at the individual properties of each document, that’s not aggregation. Instead you use a view that will sort by the criteria you want, and look at each document and note when the key changes.

If the goal of looking at all the documents is to compile some other aggregate info about them, try using a reduce function. (See the docs.)