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.effektif.mongo.MongoCollection.java

License:Apache License

public Iterator<BasicDBObject> aggregate(String description, List<DBObject> pipeline) {
    if (log.isDebugEnabled()) {
        log.debug("--" + dbCollection.getName() + "-> " + description + " q=" + toString(pipeline));
    }//from ww w  . ja  va2s  .c  o m
    AggregationOutput aggregationOutput = dbCollection.aggregate(pipeline);
    return new LoggingIterator(this, aggregationOutput.results().iterator());
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

private static Iterator<DBObject> setUpPipelineSample(String query, int numDocsToSample,
        DBCollection collection) throws KettleException {

    query = query + ", {$limit : " + numDocsToSample + "}"; //$NON-NLS-1$ //$NON-NLS-2$
    List<DBObject> samplePipe = jsonPipelineToDBObjectList(query);

    DBObject first = samplePipe.get(0);/*from   ww  w .jav a2 s .com*/
    DBObject[] remainder = new DBObject[samplePipe.size() - 1];
    for (int i = 1; i < samplePipe.size(); i++) {
        remainder[i - 1] = samplePipe.get(i);
    }

    AggregationOutput result = collection.aggregate(first, remainder);

    return result.results().iterator();
}

From source file:com.kurniakue.trxreader.data.TransactionD.java

public void recapitulateCustomerAtMonth(String customerName, String yearMonth) {
    List<DBObject> list = new ArrayList<>();
    list.add(b("$match", b("Date", b("$regex", yearMonth + ".*").append("$options", "i")).append("CustomerName",
            customerName)));/*from   w w w .  j  a  v a  2s .  c  om*/
    list.add(b("$group", b("_id", "$CustomerName").append("total", b("$sum", "$Amount"))));
    AggregationOutput output = transactions.aggregate(list);
    for (Iterator iterator = output.results().iterator(); iterator.hasNext();) {
        Object next = iterator.next();
        System.out.println(next);
    }
}

From source file:com.mingo.convert.ConversionUtils.java

License:Apache License

/**
 * Convert aggregation output to BasicDBList.
 *
 * @param aggregationOutput aggregation output
 * @return BasicDBList/*from   w w w .j av a  2 s  .  co  m*/
 */
public static BasicDBList getAsBasicDBList(AggregationOutput aggregationOutput) {
    Validate.notNull(aggregationOutput, "aggregation output cannot be null");
    BasicDBList result = new BasicDBList();
    result.addAll(Lists.newArrayList(aggregationOutput.results()));
    return result;
}

From source file:com.mobileman.kuravis.core.services.treatment_review_summary.impl.TreatmentReviewSummaryServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/* ww  w  .ja  va2 s .  c  o m*/
 * @see com.mobileman.kuravis.core.services.treatment_review_summary.TreatmentReviewSummaryService#diseasesIndex()
 */
@Override
public List<DBObject> diseasesIndex() {

    AggregationOutput out = getCollection().aggregate(
            new BasicDBObject("$group",
                    new BasicDBObject("_id", new BasicDBObject("$toUpper",
                            Arrays.asList(new BasicDBObject("$substr", Arrays.asList("$disease.name", 0, 1)))))
                                    .append("diseasesPerIndex", new BasicDBObject("$sum", 1))),
            new BasicDBObject("$project",
                    new BasicDBObject("index", "$_id").append("diseasesPerIndex", "$diseasesPerIndex")),
            new BasicDBObject("$sort", new BasicDBObject("index", 1))
    //new BasicDBObject("$skip", page.getOffset()),
    //new BasicDBObject("$limit", page.getPageSize())

    );

    List<DBObject> result = new ArrayList<>();
    for (DBObject dbObject : out.results()) {
        String index = (String) dbObject.get("index");
        if (index != null && index.trim().length() > 0) {
            result.add(new BasicDBObject("index", index).append("diseasesPerIndex",
                    dbObject.get("diseasesPerIndex")));
        }
    }

    return result;
}

From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/*from  w  ww  .  ja v a2 s. c om*/
 * @see com.mobileman.kuravis.core.services.user.UserService#findUsersByDiseaseAndTreatment(com.mongodb.DBObject, Pageable)
 */
@Override
public List<DBObject> findUsersByDiseaseAndTreatment(DBObject query, Pageable page) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

    if (query != null) {
        if (query.containsField("diseaseId")) {
            builder.add("disease." + EntityUtils.ID, query.get("diseaseId"));
        }

        if (query.containsField("treatmentId")) {
            builder.add("treatment." + EntityUtils.ID, query.get("treatmentId"));
        }
    }

    AggregationOutput out = getCollection(TreatmentReview.ENTITY_NAME).aggregate(
            new BasicDBObject("$match", builder.get()),
            new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("_id", "$author._id"))),
            new BasicDBObject("$project", new BasicDBObject(EntityUtils.ID, "$_id._id")),
            new BasicDBObject("$skip", page.getOffset()), new BasicDBObject("$limit", page.getPageSize())

    );

    List<DBObject> result = new ArrayList<>();
    Set<String> userIds = new HashSet<String>();
    for (DBObject dbObject : out.results()) {
        String userId = EntityUtils.getEntityId(dbObject);
        userIds.add(userId);
        result.add(dbObject);
    }

    Map<String, DBObject> usersData = findUsersData(userIds, "name", "gender", "settings.profile");
    for (DBObject user : result) {
        DBObject data = usersData.get(EntityUtils.getEntityId(user));
        if (data != null) {
            user.put("name", data.get("name"));
            user.put("gender", data.get("gender"));
            user.put("settings", data.get("settings"));
        }
    }

    return result;
}

From source file:com.mobileman.moments.core.services.user.impl.UserStatsServiceImpl.java

License:Apache License

/**
 * @param userId/*from   w  w w .  j av  a  2 s. c  o m*/
 */
private void computeNumberOfQuestions(final ObjectId userId) {
    mongoTemplate.execute(Question.class, new CollectionCallback<Void>() {

        @Override
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            final List<DBObject> pipeline = new ArrayList<DBObject>();
            pipeline.add(new BasicDBObject("$match", new BasicDBObject("created_by._id", userId)));
            pipeline.add(new BasicDBObject("$group",
                    new BasicDBObject("_id", null).append("count", new BasicDBObject("$sum", 1))));
            AggregationOutput aggregationOutput = collection.aggregate(pipeline);
            long questionCount = 0;
            for (DBObject result : aggregationOutput.results()) {
                questionCount = Number.class.cast(result.get("count")).longValue();
                break;
            }

            mongoTemplate.findAndModify(Query.query(Criteria.where("_id").is(userId)),
                    new Update().set("userStats.numberOfQuestions", questionCount), User.class);

            return null;
        }
    });
}

From source file:com.seer.datacruncher.jpa.dao.MongoDbDao.java

License:Open Source License

/**
 * Gets data for Annual, Detailed, Monthly reports.
 *
 *        db.jv_datastreams.aggregate({$match : {id_application : 2}},
 *    {$project : {_id : 0, checked : 1, received_date : 1}},
 *    {$group: { _id: "$checked", result_sum : {$sum : 1}, result_date :
 *    {$first : "$received_date"}}})/*from w w w.  j a  v  a  2  s.c o m*/
 *    + date_range
 *
 * @return reports data
 */
public static List<?> getList(ReportType type, int appId, int schemaId, Calendar currentDate) {
    List<Object> list = new ArrayList<Object>();
    DBCollection coll = getDatastreamsCollection();
    if (type == ReportType.MONTHLY || type == ReportType.ANNUAL || type == ReportType.DETAILED) {
        // $match operation
        DBObject matchFields = new BasicDBObject(_APP_ID, appId);
        if (type == ReportType.DETAILED) {
            matchFields.put(_SCHEMA_ID, schemaId);
        }
        DBObject dateRange = new BasicDBObject("$gt", ReportsUtils.getStartDate(type, currentDate));
        dateRange.put("$lt", ReportsUtils.getEndDate(type, currentDate));
        matchFields.put(_RECEIVED_DATE, dateRange);
        DBObject match = new BasicDBObject("$match", matchFields);
        // $projection operation
        DBObject fields = new BasicDBObject("_id", 0);
        fields.put(_CHECKED, 1);
        fields.put(_RECEIVED_DATE, 1);
        DBObject project = new BasicDBObject("$project", fields);
        // $group operation
        DBObject groupFields = new BasicDBObject("_id", "$" + _CHECKED);
        final String resultSum = "result_sum";
        final String resultDate = "result_date";
        groupFields.put(resultSum, new BasicDBObject("$sum", 1));
        groupFields.put(resultDate, new BasicDBObject("$first", "$" + _RECEIVED_DATE));
        DBObject group = new BasicDBObject("$group", groupFields);
        AggregationOutput aggr = coll.aggregate(match, project, group);
        Iterator<DBObject> it = aggr.results().iterator();
        while (it.hasNext()) {
            DBObject obj = it.next();
            Object[] arr = new Object[3];
            arr[0] = obj.get("_id");
            arr[1] = obj.get(resultSum);
            arr[2] = new SimpleDateFormat("yyyy-MM-dd").format(obj.get(resultDate));
            list.add(arr);
        }
    }
    return list;
}

From source file:com.seer.datacruncher.jpa.dao.MongoDbDao.java

License:Open Source License

/**
 * Gets data for Donut and RealTime report.
 *
 *        db.jv_datastreams.aggregate({$match : {id_application : 2}},
 *    {$project : {_id : 0, checked : 1, received_date : 1}},
 *    {$group: { _id: "$checked", result_sum : {$sum : 1}, result_date :
 *    {$first : "$received_date"}}})//w  ww .ja  va  2 s.  c o  m
 *    + date_range
 *
 * @return
 */
public static List<?> getList(int appId, int schemaId, int year, int month, Calendar currentDate,
        boolean isDonut) {
    List<Object> list = new ArrayList<Object>();
    DBCollection coll = getDatastreamsCollection();
    DBObject matchFields = new BasicDBObject();
    if (isDonut) {
        matchFields.put(_APP_ID, appId);
        if (schemaId != 0) {
            matchFields.put(_SCHEMA_ID, schemaId);
        }
    }
    DBObject dateRange = new BasicDBObject("$gt", isDonut ? ReportsUtils.getDonutStartDate(year, month)
            : ReportsUtils.getStartDate(ReportType.REAL_TIME, currentDate));
    dateRange.put("$lt", isDonut ? ReportsUtils.getDonutEndDate(year, month)
            : ReportsUtils.getEndDate(ReportType.REAL_TIME, currentDate));
    matchFields.put(_RECEIVED_DATE, dateRange);
    DBObject match = new BasicDBObject("$match", matchFields);
    // $projection operation
    DBObject fields = new BasicDBObject("_id", 0);
    fields.put(_CHECKED, 1);
    DBObject project = new BasicDBObject("$project", fields);
    // $group operation
    DBObject groupFields = new BasicDBObject("_id", "$" + _CHECKED);
    final String resultSum = "result_sum";
    groupFields.put(resultSum, new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);
    AggregationOutput aggr = coll.aggregate(match, project, group);
    Iterator<DBObject> it = aggr.results().iterator();
    while (it.hasNext()) {
        DBObject obj = it.next();
        Object[] arr = new Object[2];
        arr[0] = obj.get("_id");
        arr[1] = Long.valueOf((Integer) obj.get(resultSum));
        list.add(arr);
    }
    return list;
}

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

License:Open Source License

@Override
public Map<TimePeriod, Double> getUnknownFailureCauseQuotaPerTime(int intervalSize, GraphFilterBuilder filter) {
    Map<TimePeriod, Integer> unknownFailures = new HashMap<TimePeriod, Integer>();
    Map<TimePeriod, Integer> knownFailures = new HashMap<TimePeriod, Integer>();
    Set<TimePeriod> periods = new HashSet<TimePeriod>();

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

    // Use $project to change all null failurecauses to 'false' since
    // it's not possible to group by 'null':
    DBObject projectFields = new BasicDBObject();
    projectFields.put("startingTime", 1);
    DBObject nullToFalse = new BasicDBObject("$ifNull", asList("$failureCauses", false));
    projectFields.put("failureCauses", nullToFalse);
    DBObject project = new BasicDBObject("$project", projectFields);

    // Group by date and false/non false failure causes:
    DBObject idFields = generateTimeGrouping(intervalSize);
    DBObject checkNullFailureCause = new BasicDBObject("$eq", asList("$failureCauses", false));
    idFields.put("isNullFailureCause", checkNullFailureCause);
    DBObject groupFields = new BasicDBObject();
    groupFields.put("_id", idFields);
    groupFields.put("number", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    AggregationOutput output;
    try {/*w w w .j  a  v  a 2s  . c  o  m*/
        output = getStatisticsCollection().aggregate(match, project, group);
        for (DBObject result : output.results()) {
            DBObject groupedAttrs = (DBObject) result.get("_id");
            TimePeriod period = generateTimePeriodFromResult(result, intervalSize);
            periods.add(period);
            int number = (Integer) result.get("number");
            boolean isNullFailureCause = (Boolean) groupedAttrs.get("isNullFailureCause");
            if (isNullFailureCause) {
                unknownFailures.put(period, number);
            } else {
                knownFailures.put(period, number);
            }
        }
    } catch (Exception e) {
        logger.fine("Unable to get unknown failure cause quota per time");
        e.printStackTrace();
    }
    Map<TimePeriod, Double> nullFailureCauseQuotas = new HashMap<TimePeriod, Double>();
    for (TimePeriod timePeriod : periods) {
        int unknownFailureCount = 0;
        int knownFailureCount = 0;
        if (unknownFailures.containsKey(timePeriod)) {
            unknownFailureCount = unknownFailures.get(timePeriod);
        }
        if (knownFailures.containsKey(timePeriod)) {
            knownFailureCount = knownFailures.get(timePeriod);
        }
        double quota;
        if (unknownFailureCount == 0) {
            quota = 0d;
        } else {
            quota = ((double) unknownFailureCount) / (unknownFailureCount + knownFailureCount);
        }
        nullFailureCauseQuotas.put(timePeriod, quota);
    }
    return nullFailureCauseQuotas;
}