1

This is a follow-up to the question here Using map/reduce for mapping the properties in a collection.

I currently have a collection containing documents where each document is a form submission. There are multiple forms submissions held within a single mongoDB collection and can be differentiated from one another by the value held within a (key, value) pair with key=formID. I currently have a very lazy method (below) for finding all the keys for documents with a specific formID, however hoped that it would be possible to optimize this by using MongoDBs MapReduce functionality.

Bson bsonFilter = Filters.eq("formid", formId);
FindIterable<Document> submissionsById = collection.find(bsonFilter);
Set<String> keys = new HashSet<>();
for (Document submission : submissionsById){
    keys.addAll(submission.keySet());
}

JSONArray keysArray = new JSONArray();
keys.forEach(keysArray::put);

Is this possible, or is the rudimentary solution I've come up with going to be as good as I can manage? Thanks.

Vincent Doba
  • 4,343
  • 3
  • 22
  • 42
alexic0n_
  • 19
  • 2
  • If you are just looking for top level keys (looks like it as per your code), you can do an aggregation query to get all the keys as an array list of strings. – prasad_ Oct 28 '21 at 12:09

0 Answers0