How to search with a set of keys and also aggregate by count in CouchbaseLite?

I have a document that looks like this:

   _id: <someDocId>,
   tags: ["tag1", "tag2", "tag3"]
   docType: ...

Given a set of ids or docIds (an array of _id), how can I get the query results that look like this?

"tag1", 3 // 3 of the _ids provided have this tag
"tag2", 2

I started with this CBLView mapblock and in the reduce block, I counted the values:

if let tags = doc["tags"] as? [String], 
   let docId = doc["_id"] as? String { // didn't include other conditions for brevity
   for tag in tags {
      emit([tag, mediaId], mediaId)

But with this view and the result that I want, I’m not sure how I’m supposed to setup the CBLQuery since this won’t work:

let docIds = [...]
query.keys = docIds // I'm not sure where I'm supposed to set the keys...
query.groupLevel = 2

I’m using couchbase-lite-ios (1.4.0). I hope someone can point me in the right direction.

You can’t do that with a query in 1.x. A view is basically an index, and there’s no index that’s going to help with this query because it’s over an arbitrary set of documents and an arbitrary set of tags.

You can implement this by iterating over the docIDs, loading each document, and adding its tags to a CountedSet structure.