Example usage for com.mongodb AggregationOutput results

List of usage examples for com.mongodb AggregationOutput results

Introduction

In this page you can find the example usage for com.mongodb AggregationOutput results.

Prototype

List results

To view the source code for com.mongodb AggregationOutput results.

Click Source Link

Usage

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public List<ObjectCountPair<String>> getNbrOfFailureCausesPerId(GraphFilterBuilder filter, int maxNbr) {
    List<ObjectCountPair<String>> nbrOfFailureCausesPerId = new ArrayList<ObjectCountPair<String>>();
    DBObject matchFields = generateMatchFields(filter);
    DBObject match = new BasicDBObject("$match", matchFields);

    DBObject unwind = new BasicDBObject("$unwind", "$failureCauses");

    DBObject groupFields = new BasicDBObject();
    groupFields.put("_id", "$failureCauses.failureCause");
    groupFields.put("number", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("number", -1));

    DBObject limit = null;//w  ww.j  a v a2  s .com
    if (maxNbr > 0) {
        limit = new BasicDBObject("$limit", maxNbr);
    }

    AggregationOutput output;
    try {
        if (limit == null) {
            output = getStatisticsCollection().aggregate(match, unwind, group, sort);
        } else {
            output = getStatisticsCollection().aggregate(match, unwind, group, sort, limit);
        }
        for (DBObject result : output.results()) {
            DBRef failureCauseRef = (DBRef) result.get("_id");
            if (failureCauseRef != null) {
                Integer number = (Integer) result.get("number");
                String id = failureCauseRef.getId().toString();
                nbrOfFailureCausesPerId.add(new ObjectCountPair<String>(id, number));
            }
        }
    } catch (Exception e) {
        logger.fine("Unable to get failure causes per id");
        e.printStackTrace();
    }

    return nbrOfFailureCausesPerId;
}

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public Date getLatestFailureForCause(String id) {

    DBObject causeToMatch = new BasicDBObject("$ref", "failureCauses");
    causeToMatch.put("$id", new ObjectId(id));

    DBObject causeList = new BasicDBObject("failureCauses.failureCause", causeToMatch);

    DBObject match = new BasicDBObject("$match", causeList);
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("startingTime", -1));
    DBObject limit = new BasicDBObject("$limit", 1);

    AggregationOutput output;
    try {/*from  w w  w  .  j a va  2  s  .  com*/
        output = getStatisticsCollection().aggregate(match, sort, limit);

        for (DBObject result : output.results()) {
            Date startingTime = (Date) result.get("startingTime");

            if (startingTime != null) {
                return startingTime;
            }
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed getting latest failure of cause", e);
    }

    return null;
}

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public Map<Integer, List<FailureCause>> getFailureCausesPerBuild(GraphFilterBuilder filter) {
    Map<Integer, List<FailureCause>> nbrOfFailureCausesPerBuild = new HashMap<Integer, List<FailureCause>>();
    DBObject matchFields = generateMatchFields(filter);
    DBObject match = new BasicDBObject("$match", matchFields);

    DBObject unwind = new BasicDBObject("$unwind", "$failureCauses");

    DBObject groupFields = new BasicDBObject("_id", "$buildNumber");
    groupFields.put("failureCauses", new BasicDBObject("$addToSet", "$failureCauses.failureCause"));
    DBObject group = new BasicDBObject("$group", groupFields);

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));

    AggregationOutput output;
    try {// w  ww.  j  av a 2 s  . co  m
        output = getStatisticsCollection().aggregate(match, unwind, group, sort);
        for (DBObject result : output.results()) {
            List<FailureCause> failureCauses = new ArrayList<FailureCause>();
            Integer buildNumber = (Integer) result.get("_id");
            BasicDBList failureCauseRefs = (BasicDBList) result.get("failureCauses");
            for (Object o : failureCauseRefs) {
                DBRef failureRef = (DBRef) o;
                String id = failureRef.getId().toString();
                FailureCause failureCause = getCause(id);
                failureCauses.add(failureCause);
            }

            nbrOfFailureCausesPerBuild.put(buildNumber, failureCauses);
        }
    } catch (Exception e) {
        logger.fine("Unable to count failure causes by build");
        e.printStackTrace();
    }

    return nbrOfFailureCausesPerBuild;
}

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public List<FailureCauseTimeInterval> getFailureCausesPerTime(int intervalSize, GraphFilterBuilder filter,
        boolean byCategories) {
    List<FailureCauseTimeInterval> failureCauseIntervals = new ArrayList<FailureCauseTimeInterval>();
    Map<MultiKey, FailureCauseTimeInterval> categoryTable = new HashMap<MultiKey, FailureCauseTimeInterval>();

    DBObject matchFields = generateMatchFields(filter);
    DBObject match = new BasicDBObject("$match", matchFields);

    DBObject unwind = new BasicDBObject("$unwind", "$failureCauses");

    DBObject idFields = generateTimeGrouping(intervalSize);
    idFields.put("failureCause", "$failureCauses.failureCause");
    DBObject groupFields = new BasicDBObject();
    groupFields.put("_id", idFields);
    groupFields.put("number", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    AggregationOutput output;
    try {/*from  w ww . j  a  v  a 2  s . c om*/
        output = getStatisticsCollection().aggregate(match, unwind, group);
        for (DBObject result : output.results()) {
            int number = (Integer) result.get("number");

            TimePeriod period = generateTimePeriodFromResult(result, intervalSize);

            BasicDBObject groupedAttrs = (BasicDBObject) result.get("_id");
            DBRef failureRef = (DBRef) groupedAttrs.get("failureCause");
            String id = failureRef.getId().toString();
            FailureCause failureCause = getCause(id);

            if (byCategories) {
                if (failureCause.getCategories() != null) {
                    for (String category : failureCause.getCategories()) {
                        MultiKey multiKey = new MultiKey(category, period);
                        FailureCauseTimeInterval interval = categoryTable.get(multiKey);
                        if (interval == null) {
                            interval = new FailureCauseTimeInterval(period, category, number);
                            categoryTable.put(multiKey, interval);
                            failureCauseIntervals.add(interval);
                        } else {
                            interval.addNumber(number);
                        }
                    }
                }
            } else {
                FailureCauseTimeInterval timeInterval = new FailureCauseTimeInterval(period,
                        failureCause.getName(), failureCause.getId(), number);
                failureCauseIntervals.add(timeInterval);
            }
        }
    } catch (UnknownHostException e) {
        logger.fine("Unable to get failure causes by time");
        e.printStackTrace();
    } catch (AuthenticationException e) {
        logger.fine("Unable to get failure causes by time");
        e.printStackTrace();
    }

    return failureCauseIntervals;
}

From source file:com.stratio.connector.mongodb.core.engine.query.AggregationLogicalWorkflowExecutor.java

License:Apache License

/**
 * Execute an aggregation query.// w  ww  . ja  v a  2s  .co m
 *
 * @param mongoClient
 *            the MongoDB client.
 * @return the Crossdata ResultSet.
 * @throws ExecutionException
 *             if the execution fails.
 */
@Override
public ResultSet executeQuery(MongoClient mongoClient) throws ExecutionException {

    DB db = mongoClient.getDB(logicalWorkflowData.getProject().getCatalogName());
    DBCollection collection = db.getCollection(logicalWorkflowData.getProject().getTableName().getName());
    ResultSet resultSet = new ResultSet();
    resultSet.setColumnMetadata(
            MetaResultUtils.createMetadata(logicalWorkflowData.getProject(), logicalWorkflowData.getSelect()));

    // AggregationOptions aggOptions = AggregationOptions.builder()
    // .allowDiskUse(true)
    // .batchSize(size)
    // pipeline,aggOptions => dbcursor
    try {
        int stage = 1;
        for (DBObject aggregationStage : query) {
            logger.debug("Aggregate framework stage (" + (stage++) + ") : " + aggregationStage);
        }
        AggregationOutput aggOutput = collection.aggregate(query);
        for (DBObject result : aggOutput.results()) {
            if (logger.isDebugEnabled()) {
                logger.debug("AggResult: " + result);
            }
            resultSet.add(MetaResultUtils.createRowWithAlias(result, logicalWorkflowData.getSelect()));
        }
    } catch (MongoException mongoException) {
        logger.error("Error executing an aggregation query:" + mongoException.getMessage());
        throw new MongoExecutionException(mongoException.getMessage(), mongoException);
    }

    return resultSet;
}

From source file:com.tengen.home.Week1Homework3.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();

    DB database = client.getDB("m101");
    DBCollection collection = database.getCollection("funnynumbers");

    // Not necessary yet to understand this.  It's just to prove that you
    // are able to run a command on a mongod server
    AggregationOutput output = collection.aggregate(
            new BasicDBObject("$group",
                    new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))),
            new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$gt", 2))),
            new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

    int answer = 0;
    for (DBObject doc : output.results()) {
        answer += (Double) doc.get("_id");
    }//from  www . j a v  a2 s  .c o  m

    System.out.println("THE ANSWER IS: " + answer);
}

From source file:com.tengen.home.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override//from   w w w.  j  a v a2s .com
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(
                        new BasicDBObject("$group",
                                new BasicDBObject("_id", "$value").append("count",
                                        new BasicDBObject("$sum", 1))),
                        new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))),
                        new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}

From source file:DashboardServices.FetchInstances.java

@GET
@Produces(MediaType.TEXT_PLAIN)//  w w w .  j  a va  2s .  co  m
public Response getRole(@Context UriInfo info) {
    String projectId = info.getQueryParameters().getFirst("projectId");
    String entityName = info.getQueryParameters().getFirst("entityName");
    System.out.println("projectId" + projectId);
    String finalOutput = "";
    try {
        MongoClient mongoClient;
        try {
            mongoClient = new MongoClient();
            // Now connect to your databases
            DB db = mongoClient.getDB("SSKDatabase");
            //System.out.println("Connect to database successfully");
            DBCollection coll = db.getCollection("insa");

            DBObject match = new BasicDBObject("$match", new BasicDBObject("_id", projectId));
            DBObject unwind = new BasicDBObject("$unwind", "$" + entityName);
            DBObject project = new BasicDBObject("$project", new BasicDBObject("instances", "$" + entityName));

            AggregationOutput output = coll.aggregate(match, unwind, project);
            if (output != null) {
                System.out.println("Ajay worked");
            } else {
                System.out.println("ajay didnt not woek");
            }
            System.out.println("before if condition");
            for (DBObject result : output.results()) {
                System.out.println("hai i reached here");
                System.out.println(result);
                finalOutput += result;
            }
        } catch (Exception e) {
            System.out.println("error");
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.status(200).entity(finalOutput).build();
}

From source file:DashboardServices.FetchProject.java

/**
 * Retrieves representation of an instance of DashboardServices.LoginServiceResource
 * @return an instance of java.lang.String
 *///  w w  w. j  a va  2 s .  c  om

@POST
@Produces(MediaType.TEXT_PLAIN)
public Response getUsers(@Context UriInfo info) {
    String userId = info.getQueryParameters().getFirst("userId");
    String finalOutput = "";

    try {
        MongoClient mongoClient;

        try {
            mongoClient = new MongoClient();
            // Now connect to your databases
            DB db = mongoClient.getDB("SSKDatabase");
            //System.out.println("Connect to database successfully");
            DBCollection coll = db.getCollection("UserCollection");

            //DBCollection coll2 = db.getCollection("ProjectCollection");

            DBObject match = new BasicDBObject("$match", new BasicDBObject("_id", userId));

            DBObject unwind = new BasicDBObject("$unwind", new BasicDBObject("path", "$projects"));

            DBObject lookup = new BasicDBObject("$lookup",
                    new BasicDBObject("from", "ProjectCollection")
                            .append("localField", "projects.projectIndexId").append("foreignField", "_id")
                            .append("as", "productObjects"));

            DBObject unwind2 = new BasicDBObject("$unwind", "$productObjects");

            DBObject group = new BasicDBObject("$group",
                    new BasicDBObject("_id", "$_id").append("projects", new BasicDBObject("$push", "$projects"))
                            .append("productObjects", new BasicDBObject("$push", "$productObjects")));
            DBObject group2 = new BasicDBObject("$group",
                    new BasicDBObject("_id", "$productObjects.projectName"));

            //System.out.println("Collection mycol selected successfully");

            AggregationOutput output = coll.aggregate(match, unwind, lookup, unwind2, group, group2);

            for (DBObject result : output.results()) {
                System.out.println(result);
                finalOutput += result;
            }

        } catch (Exception e) {
            System.out.println("error");
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return Response.status(200).entity(finalOutput).build();

}

From source file:DashboardServices.Fetchrole.java

@POST
@Produces(MediaType.TEXT_PLAIN)/*from w w  w.j  a  v  a 2  s .co  m*/
public Response getRole(@Context UriInfo info) {
    String userId = info.getQueryParameters().getFirst("userId");
    String projectname = info.getQueryParameters().getFirst("projectname");
    String finalOutput = "";
    try {
        MongoClient mongoClient;
        try {
            mongoClient = new MongoClient();
            // Now connect to your databases
            DB db = mongoClient.getDB("SSKDatabase");
            //System.out.println("Connect to database successfully");
            DBCollection coll = db.getCollection("ProjectCollection");
            DBObject match = new BasicDBObject("$match", new BasicDBObject("projectName", projectname));
            DBObject lookup = new BasicDBObject("$lookup",
                    new BasicDBObject("from", "UserCollection").append("localField", "_id")
                            .append("foreignField", "projects.projectIndexId").append("as", "productObjects"));
            DBObject unwind = new BasicDBObject("$unwind", "$productObjects");
            DBObject match2 = new BasicDBObject("$match", new BasicDBObject("productObjects._id", userId));
            DBObject unwind2 = new BasicDBObject("$unwind", "$productObjects.projects");
            DBObject match3 = new BasicDBObject("$match",
                    new BasicDBObject("productObjects.projects.projectName", projectname));
            DBObject project = new BasicDBObject("$project",
                    new BasicDBObject("productObjects.projects.projectRole", 1).append("_id", 0));
            DBObject group = new BasicDBObject("$group",
                    new BasicDBObject("_id", "$productObjects.projects.projectRole"));
            AggregationOutput output = coll.aggregate(match, lookup, unwind, match2, unwind2, match3, project,
                    group);
            for (DBObject result : output.results()) {
                System.out.println(result);
                finalOutput += result;
            }
        } catch (Exception e) {
            System.out.println("error");
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.status(200).entity(finalOutput).build();
}