Example usage for org.springframework.data.mongodb.core.mapreduce GroupByResults GroupByResults

List of usage examples for org.springframework.data.mongodb.core.mapreduce GroupByResults GroupByResults

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.mapreduce GroupByResults GroupByResults.

Prototype

public GroupByResults(List<T> mappedResults, Document rawResults) 

Source Link

Usage

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

public <T> GroupByResults<T> group(Criteria criteria, String inputCollectionName, GroupBy groupBy,
        Class<T> entityClass) {

    DBObject dbo = groupBy.getGroupByObject();
    dbo.put("ns", inputCollectionName);

    if (criteria == null) {
        dbo.put("cond", null);
    } else {//from w w  w . j a  va  2  s  .co  m
        dbo.put("cond", mapper.getMappedObject(criteria.getCriteriaObject(), null));
    }
    // If initial document was a JavaScript string, potentially loaded by Spring's Resource abstraction, load it and
    // convert to DBObject

    if (dbo.containsField("initial")) {
        Object initialObj = dbo.get("initial");
        if (initialObj instanceof String) {
            String initialAsString = replaceWithResourceIfNecessary((String) initialObj);
            dbo.put("initial", JSON.parse(initialAsString));
        }
    }

    if (dbo.containsField("$reduce")) {
        dbo.put("$reduce", replaceWithResourceIfNecessary(dbo.get("$reduce").toString()));
    }
    if (dbo.containsField("$keyf")) {
        dbo.put("$keyf", replaceWithResourceIfNecessary(dbo.get("$keyf").toString()));
    }
    if (dbo.containsField("finalize")) {
        dbo.put("finalize", replaceWithResourceIfNecessary(dbo.get("finalize").toString()));
    }

    DBObject commandObject = new BasicDBObject("group", dbo);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Executing Group with DBObject [%s]", serializeToJsonSafely(commandObject)));
    }

    CommandResult commandResult = executeCommand(commandObject, getDb().getOptions());
    handleCommandError(commandResult, commandObject);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Group command result = [" + commandResult + "]");
    }

    @SuppressWarnings("unchecked")
    Iterable<DBObject> resultSet = (Iterable<DBObject>) commandResult.get("retval");

    List<T> mappedResults = new ArrayList<T>();
    DbObjectCallback<T> callback = new ReadDbObjectCallback<T>(mongoConverter, entityClass);
    for (DBObject dbObject : resultSet) {
        mappedResults.add(callback.doWith(dbObject));
    }
    GroupByResults<T> groupByResult = new GroupByResults<T>(mappedResults, commandResult);
    return groupByResult;

}