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:net.tooan.ynpay.third.mongodb.BuguAggregation.java

License:Apache License

public Iterable<DBObject> results() throws AggregationException {
    int size = pipeline.size();
    if (size <= 0) {
        throw new AggregationException("Empty pipeline in aggregation!");
    }//from   ww w .j a va 2s .c  o  m
    AggregationOutput output = null;
    if (size == 1) {
        output = coll.aggregate(pipeline.get(0));
    } else {
        DBObject firstOp = pipeline.get(0);
        List<DBObject> subList = pipeline.subList(1, size);
        DBObject[] arr = subList.toArray(new DBObject[size - 1]);
        output = coll.aggregate(firstOp, arr);
    }
    CommandResult cr = output.getCommandResult();
    if (!cr.ok()) {
        throw new AggregationException(cr.getErrorMessage());
    }
    return output.results();
}

From source file:nosqltools.GroupByPanel.java

protected String executeGroupByOperation(DBCollection collection, QueryCollectionDialog parent) {
    this.parent = parent;
    AggregationOutput aggOut = null;
    String idField = this.FieldTextArea.getText();
    String valueField = this.ValueTextArea.getText();
    BasicDBObject match = new BasicDBObject("$match", new BasicDBObject(idField, valueField));
    BasicDBObject group = null;/*from ww w  .j a v a 2 s  .c  om*/
    BasicDBObject sort = null;
    this.QueryString = "";
    String groupByWith = "";
    String orderON = "";
    String orderDirection = "";

    if (this.groupByRB.isSelected()) {
        if (this.countRB.isSelected()) {
            groupByWith = Initializations.COUNT_AGGREGATE_SYNTAX;
            group = new BasicDBObject("$group", new BasicDBObject("_id", "$" + this.groupByTF.getText())
                    .append("Count", new BasicDBObject("$sum", 1)));
        } else if (this.SumRB.isSelected()) {
            groupByWith = Initializations.SUM_AGGREGATE_SYNTAX;
            group = new BasicDBObject("$group", new BasicDBObject("_id", "$" + this.groupByTF.getText())
                    .append("Sum", new BasicDBObject("$sum", "$" + this.sumTF.getText())));
        } else if (this.AvgRB.isSelected()) {
            groupByWith = Initializations.AVERAGE_AGGREGATE_SYNTAX;
            group = new BasicDBObject("$group", new BasicDBObject("_id", "$" + this.groupByTF.getText())
                    .append("Average", new BasicDBObject("$avg", "$" + this.avgTF.getText())));
        }

        //To allow group by without any matching condition...
        if ((idField == null || idField.equals("")) && (valueField == null || valueField.equals(""))) {
            if (this.parent.orderByRB.isSelected()) {
                orderON = groupByTF.getText() + " ";
                sort = getOrderByObject(groupByTF.getText());
            }

            if (sort == null) {
                QueryString += Initializations.GROUP_BY_SYNTAX + groupByTF.getText()
                        + Initializations.WITH_SYNTAX + groupByWith + "\n";
                aggOut = collection.aggregate(group);
            } else {
                QueryString += Initializations.GROUP_BY_SYNTAX + groupByTF.getText()
                        + Initializations.WITH_SYNTAX + groupByWith + "\n";
                QueryString += Initializations.ORDER_BY_SYNTAX + orderON + SortOrder + "\n";
                aggOut = collection.aggregate(group, sort);
            }
        } else {
            //Check whether order by is selected and act accordingly...
            if (this.parent.orderByRB.isSelected()) {
                if (groupByTF.getText() != "" || groupByTF.getText() != null) {
                    orderON = groupByTF.getText() + " ";
                    sort = getOrderByObject(groupByTF.getText());
                } else {
                    orderON = idField + " ";
                    sort = getOrderByObject(idField);
                }
            }

            if (sort == null) {
                QueryString += Initializations.SELECT_SYNTAX + FieldTextArea.getText() + " = "
                        + ValueTextArea.getText() + "\n";
                QueryString += Initializations.GROUP_BY_SYNTAX + groupByTF.getText()
                        + Initializations.WITH_SYNTAX + groupByWith + "\n";
                aggOut = collection.aggregate(match, group);
            } else {
                QueryString += Initializations.SELECT_SYNTAX + FieldTextArea.getText() + " = "
                        + ValueTextArea.getText() + "\n";
                QueryString += Initializations.GROUP_BY_SYNTAX + groupByTF.getText()
                        + Initializations.WITH_SYNTAX + groupByWith + "\n";
                QueryString += Initializations.ORDER_BY_SYNTAX + orderON + SortOrder + "\n";
                aggOut = collection.aggregate(match, group, sort);
            }
        }
    } else {
        if (sort == null) {
            QueryString += Initializations.SELECT_SYNTAX + FieldTextArea.getText() + " = "
                    + ValueTextArea.getText() + "\n";
            aggOut = collection.aggregate(match);
        } else {
            QueryString += Initializations.SELECT_SYNTAX + FieldTextArea.getText() + " = "
                    + ValueTextArea.getText() + "\n";
            QueryString += Initializations.ORDER_BY_SYNTAX + orderON + SortOrder + "\n";
            aggOut = collection.aggregate(match, sort);
        }
    }

    Iterator<DBObject> results = aggOut.results().iterator();

    String res = "";
    while (results.hasNext()) {
        res += results.next().toString() + "\n\n";
    }

    return res;
}

From source file:org.apache.calcite.adapter.mongodb.MongoTable.java

License:Apache License

/** Executes an "aggregate" operation on the underlying collection.
 *
 * <p>For example:/*from  ww  w.  j a  v a 2  s  .c  o  m*/
 * <code>zipsTable.aggregate(
 * "{$filter: {state: 'OR'}",
 * "{$group: {_id: '$city', c: {$sum: 1}, p: {$sum: '$pop'}}}")
 * </code></p>
 *
 * @param mongoDb MongoDB connection
 * @param fields List of fields to project; or null to return map
 * @param operations One or more JSON strings
 * @return Enumerator of results
 */
public Enumerable<Object> aggregate(final DB mongoDb, final List<Map.Entry<String, Class>> fields,
        final List<String> operations) {
    final List<DBObject> list = new ArrayList<DBObject>();
    final BasicDBList versionArray = (BasicDBList) mongoDb.command("buildInfo").get("versionArray");
    final Integer versionMajor = parseIntString(versionArray.get(0).toString());
    final Integer versionMinor = parseIntString(versionArray.get(1).toString());
    //    final Integer versionMaintenance = parseIntString(versionArray
    //      .get(2).toString());
    //    final Integer versionBuild = parseIntString(versionArray
    //      .get(3).toString());

    for (String operation : operations) {
        list.add((DBObject) JSON.parse(operation));
    }
    final DBObject first = list.get(0);
    final List<DBObject> rest = Util.skip(list);
    final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
    return new AbstractEnumerable<Object>() {
        public Enumerator<Object> enumerator() {
            final Iterator<DBObject> resultIterator;
            try {
                // Changed in version 2.6: The db.collection.aggregate() method
                // returns a cursor
                // and can return result sets of any size.
                // See: http://docs.mongodb.org/manual/core/aggregation-pipeline
                if (versionMajor > 1) {
                    // MongoDB version 2.6+
                    if (versionMinor > 5) {
                        AggregationOptions options = AggregationOptions.builder()
                                .outputMode(AggregationOptions.OutputMode.CURSOR).build();
                        // Warning - this can result in a very large ArrayList!
                        // but you should know your data and aggregate accordingly
                        ArrayList<DBObject> resultAsArrayList = new ArrayList<DBObject>(
                                Util.toList(mongoDb.getCollection(collectionName).aggregate(list, options)));
                        resultIterator = resultAsArrayList.iterator();
                    } else { // Pre MongoDB version 2.6
                        AggregationOutput result = aggregateOldWay(mongoDb.getCollection(collectionName), first,
                                rest);
                        resultIterator = result.results().iterator();
                    }
                } else { // Pre MongoDB version 2
                    AggregationOutput result = aggregateOldWay(mongoDb.getCollection(collectionName), first,
                            rest);
                    resultIterator = result.results().iterator();
                }
            } catch (Exception e) {
                throw new RuntimeException(
                        "While running MongoDB query " + Util.toString(operations, "[", ",\n", "]"), e);
            }
            return new MongoEnumerator(resultIterator, getter);
        }
    };
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

/**
* All headers except collection and database are non available for this
* operation.// ww  w.  java  2s  . co  m
* 
* @param exchange
* @throws Exception
*/
protected void doAggregate(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    DBObject query = exchange.getIn().getMandatoryBody(DBObject.class);

    // Impossible with java driver to get the batch size and number to skip
    Iterable<DBObject> dbIterator = null;
    try {
        AggregationOutput aggregationResult = null;

        // Allow body to be a pipeline
        // @see http://docs.mongodb.org/manual/core/aggregation/
        if (query instanceof BasicDBList) {
            BasicDBList queryList = (BasicDBList) query;
            aggregationResult = dbCol.aggregate((DBObject) queryList.get(0),
                    queryList.subList(1, queryList.size()).toArray(new BasicDBObject[queryList.size() - 1]));
        } else {
            aggregationResult = dbCol.aggregate(query);
        }

        dbIterator = aggregationResult.results();
        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.aggregate);
        resultMessage.setBody(dbIterator);

        // Mongo Driver does not allow to read size and to paginate aggregate result
    } catch (Exception e) {
        // rethrow the exception
        throw e;
    }
}

From source file:org.apache.rya.mongodb.iter.RyaStatementCursorIterator.java

License:Apache License

private void findNextValidCursor() {
    while (queryIterator.hasNext()) {
        final DBObject currentQuery = queryIterator.next();

        // Executing redact aggregation to only return documents the user
        // has access to.
        final List<DBObject> pipeline = new ArrayList<>();
        pipeline.add(new BasicDBObject("$match", currentQuery));
        pipeline.addAll(AggregationUtil.createRedactPipeline(auths));
        log.debug(pipeline);/*ww  w . j  a va 2s.co m*/
        final AggregationOutput output = coll.aggregate(pipeline);
        resultsIterator = output.results().iterator();
        if (resultsIterator.hasNext()) {
            break;
        }
    }
}

From source file:org.baldeapi.v1.persistence.GenericDAO.java

License:Apache License

public DBObject aggregateFirstResult(DBObject firstOp, DBObject... additionalOps) {
    AggregationOutput result = this.aggregate(firstOp, additionalOps);
    for (DBObject object : result.results()) {
        return object;
    }/* w w w.  jav a  2s . c o  m*/
    return null;
}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * This method is for aggregating with all pipeline options. All the options
 * should be given in sequence like: ('$group:{..}',...).
 * @param handler database handler//from  w  ww .  j a  v  a  2 s .  c o  m
 * @param col collection name
 * @param first aggregation compulsary
 * @param additionalOps other pipeline options in sequence.
 * @return Item
 * @throws QueryException
 */
public Item aggregate(final Str handler, final Item col, final Item first, final Value additionalOps)
        throws Exception {
    final DB db = getDbHandler(handler);
    AggregationOutput agg;
    DBObject[] pipeline = null;
    if (additionalOps != null && (!additionalOps.isEmpty())) {
        if (additionalOps instanceof Map) {
            pipeline = mapToDBObjectArray((Map) additionalOps);
        } else {
            int length = (int) additionalOps.size();
            if (length > 0) {
                pipeline = new BasicDBObject[length];
                int i = 0;
                for (Item x : additionalOps) {
                    pipeline[i++] = getDbObjectFromStr(x);
                }
            } else {
                pipeline = null;
            }
        }
    }
    db.requestStart();
    try {
        if (additionalOps != null && (!additionalOps.isEmpty())) {
            agg = db.getCollection(itemToString(col)).aggregate(getDbObjectFromStr(first), pipeline);
        } else {
            agg = db.getCollection(itemToString(col)).aggregate(getDbObjectFromStr(first));
        }
        final Iterable<DBObject> d = agg.results();
        return returnResult(handler, Str.get(JSON.serialize(d)));
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }

}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * This method is for aggregating with all pipeline options. All the options
 * should be given in sequence like: ('$group:{..}',...).
 * @param handler database handler database handler
 * @param col collection name/*from   w  ww. j a v  a  2 s .co  m*/
 * @param first aggregation compulsary
 * @param additionalOps other pipeline options in sequence.
 * @return Item
 * @throws Exception exception
 */
public Item aggregate(final Str handler, final Item col, final Item first, final Value additionalOps)
        throws Exception {
    final DB db = getDbHandler(handler);
    AggregationOutput agg;
    DBObject[] pipeline = null;
    if (additionalOps != null && (!additionalOps.isEmpty())) {
        if (additionalOps instanceof Map) {
            pipeline = mapToDBObjectArray((Map) additionalOps);
        } else {
            int length = (int) additionalOps.size();
            if (length > 0) {
                pipeline = new BasicDBObject[length];
                int i = 0;
                for (Item x : additionalOps) {
                    pipeline[i++] = getDbObjectFromItem(x);
                }
            }
        }
    }
    db.requestStart();
    try {
        if (additionalOps != null && (!additionalOps.isEmpty())) {
            agg = db.getCollection(itemToString(col)).aggregate(getDbObjectFromItem(first), pipeline);
        } else {
            agg = db.getCollection(itemToString(col)).aggregate(getDbObjectFromItem(first));
        }
        final Iterable<DBObject> d = agg.results();
        return returnResult(handler, Str.get(JSON.serialize(d)));
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }

}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

private MongoCollectionResult aggregate(MongoQueryOptions mongoQueryOptions,
        MongoCollectionResult mongoCollectionResult, DBCollection collection) {
    AggregationOutput aggregate = collection.aggregate(mongoQueryOptions.getOperations());
    int index = 0;
    Iterator<DBObject> iterator = aggregate.results().iterator();
    while (iterator.hasNext() && index < mongoQueryOptions.getResultLimit()) {
        mongoCollectionResult.add(iterator.next());
    }// ww  w.ja v a  2s  .  co m
    return mongoCollectionResult;
}

From source file:org.codinjutsu.tools.nosql.mongo.logic.MongoClient.java

License:Apache License

private MongoResult aggregate(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult,
        DBCollection collection) {/*from   w  w w.  java 2s  .c om*/
    AggregationOutput aggregate = collection.aggregate(mongoQueryOptions.getOperations());
    int index = 0;
    Iterator<DBObject> iterator = aggregate.results().iterator();
    while (iterator.hasNext() && index < mongoQueryOptions.getResultLimit()) {
        mongoResult.add(iterator.next());
    }
    return mongoResult;
}