Example usage for com.mongodb DBCollection aggregate

List of usage examples for com.mongodb DBCollection aggregate

Introduction

In this page you can find the example usage for com.mongodb DBCollection aggregate.

Prototype

@Deprecated
public AggregationOutput aggregate(final List<? extends DBObject> pipeline) 

Source Link

Document

Method implements aggregation framework.

Usage

From source file:mongodb.tedc.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws IOException {
    /* ------------------------------------------------------------------------ */
    /* You should do this ONLY ONCE in the whole application life-cycle:        */

    /* Create and adjust the configuration singleton */
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
    cfg.setDirectoryForTemplateLoading(new File("src/main/resources"));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);

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

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

    get("/", (req, res) -> {

        StringWriter writer = new StringWriter();
        try {/*  w  w w .j ava  2  s . c  o  m*/
            // Not necessary yet to understand this.  It's just to prove that you
            // are able to run a command on a mongod server
            DBObject groupFields = new BasicDBObject("_id", "$value");
            groupFields.put("count", new BasicDBObject("$sum", 1));
            DBObject group = new BasicDBObject("$group", groupFields);

            DBObject match = new BasicDBObject("$match",
                    new BasicDBObject("count", new BasicDBObject("$lte", 2)));

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

            // run aggregation
            List<DBObject> pipeline = Arrays.asList(group, match, sort);

            AggregationOutput output = collection.aggregate(pipeline);

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

            /* Create a data-model */
            Map<String, String> answerMap = new HashMap<>();
            answerMap.put("answer", Integer.toString(answer));

            /* Get the template (uses cache internally) */
            Template helloTemplate = cfg.getTemplate("answer.ftl");

            /* Merge data-model with template */
            helloTemplate.process(answerMap, writer);

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

From source file:nosqltools.GroupByPanel.java

protected String executeGroupByOperation(DBCollection collection, QueryCollectionDialog parent) {
    this.parent = parent;
    AggregationOutput aggOut = null;//  w w  w.ja v a 2 s. c  o m
    String idField = this.FieldTextArea.getText();
    String valueField = this.ValueTextArea.getText();
    BasicDBObject match = new BasicDBObject("$match", new BasicDBObject(idField, valueField));
    BasicDBObject group = null;
    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.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());
    }//from   ww w.  j  av  a2 s . 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) {
    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());
    }//  w  ww .j a v a 2  s .c om
    return mongoResult;
}

From source file:org.exist.mongodb.xquery.mongodb.collection.Aggregate.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//  w  ww.  java2  s . c om
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        // Get parameters
        String dbname = args[1].itemAt(0).getStringValue();
        String collection = args[2].itemAt(0).getStringValue();
        List<DBObject> pipeline = convertPipeline(args[3]);

        // Get collection in database
        DB db = client.getDB(dbname);
        DBCollection dbcol = db.getCollection(collection);

        // Execute query      
        AggregationOutput aggrOutput = dbcol.aggregate(pipeline);

        // Parse results
        Sequence retVal = new ValueSequence();

        for (DBObject result : aggrOutput.results()) {
            retVal.add(new StringValue(result.toString()));
        }

        return retVal;

    } catch (JSONParseException ex) {
        LOG.error(ex.getMessage());
        throw new XPathException(this, MongodbModule.MONG0004, ex.getMessage());

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());

    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage());
    }

}

From source file:pa036.sprava_uziv_profilov.nosql.persistence.RestaurantPersistence.java

/**
 * Gets average rating of the selected restaurant
 * @param restaurantId/*  w  ww. ja  v  a  2  s.  com*/
 * @return average rating of the selected restaurant
 */
public double getRating(String restaurantId) {
    /*JacksonDBCollection<Restaurant, String> coll = JacksonDBCollection.wrap(database.getCollection("Restaurants"), Restaurant.class,
    String.class);
    int ratingSum = 0;
    Restaurant r = findById(restaurantId);        
    for(Review re : r.getReviews())
    {
    ratingSum += re.getRating();
    }
    return (double) ratingSum / r.getReviews().size();*/

    DBCollection coll = database.getCollection("Restaurants");

    DBObject match = new BasicDBObject("$match", new BasicDBObject("_id", new ObjectId(restaurantId)));
    // create the pipeline operations, first with the $unwind
    DBObject unwind = new BasicDBObject("$unwind", "$reviews");

    // build the $group operations
    DBObject groupFields = new BasicDBObject("_id", restaurantId);
    groupFields.put("avg_rating", new BasicDBObject("$avg", "$reviews.rating"));

    DBObject group = new BasicDBObject("$group", groupFields);
    List<DBObject> pipeline = Arrays.asList(match, unwind, group);

    AggregationOutput output = coll.aggregate(pipeline);
    double r = -1;
    for (DBObject result : output.results()) {
        System.out.println(result);
        r = (double) result.get("avg_rating");
    }
    System.out.println(r);
    return r;

}

From source file:utils.ExternalResources.java

public static Map<String, Map<String, Integer>> initAPs(final String mongoHostname, final int port)
        throws FileNotFoundException, IOException {
    Map<String, Map<String, Integer>> aps = new HashMap<String, Map<String, Integer>>();

    MongoClient mongoClient = new MongoClient(mongoHostname, port);
    DBCollection collection = mongoClient.getDB("AR").getCollection("aps");

    // we need to merge namespace with name
    // {$project : { name : {$concat: ["$namespace", "-", "$name"]}, groups:1}}
    BasicDBList concatArgs = new BasicDBList();
    concatArgs.add("$namespace");
    concatArgs.add("-");
    concatArgs.add("$name");
    DBObject project = new BasicDBObject("$project",
            new BasicDBObject("name", new BasicDBObject("$concat", concatArgs)).append("groups", 1)
                    .append("poems", 1));

    AggregationOutput output = collection.aggregate(project);

    // For each AP
    for (DBObject dbo : output.results()) {
        Map<String, Integer> sfGroup = new HashMap<String, Integer>();
        aps.put((String) dbo.get("name"), sfGroup);

        BasicDBList l = (BasicDBList) dbo.get("groups");

        int groupID = 0;
        // For each group
        for (Object o : l) {
            BasicDBList dbl = (BasicDBList) o;

            // For each service flavour
            for (Object sf : dbl) {
                sfGroup.put((String) sf, groupID);
            }//from  w  w w  .  j  a va  2 s.  c om

            groupID++;
        }
    }

    mongoClient.close();
    return aps;
}

From source file:yelpmongodb.hw4.java

private void queryBusinesses(double[] poi, int proximity, ArrayList<String> maincat, ArrayList<String> att) {
    MongoClient client = new MongoClient();
    DB db = client.getDB("db");
    DBCollection coll = db.getCollection("business");
    String[] arr = { "$longitude", "$latitude" };
    List<DBObject> aggregate = new ArrayList<>();

    DBObject project = BasicDBObjectBuilder.start().push("$project").add("loc", arr)
            .add("business_id", "$business_id").add("name", "$name").add("city", "$city").add("state", "$state")
            .add("stars", "$stars").add("attributes", "$attributes").add("categories", "$categories").get();
    DBObject geoMatch = getGeoQuery(poi, proximity, 3963.2);
    DBObject mainMatch = mainCategoriesQuery(maincat, 1);
    DBObject attMatch = attributesQuery(att);
    aggregate.add(project);/*from   ww  w.jav a 2 s  .  c  o m*/
    aggregate.add(geoMatch);
    aggregate.add(mainMatch);
    aggregate.add(attMatch);
    AggregationOutput aggrcurs = coll.aggregate(aggregate);
    Iterable<DBObject> res = aggrcurs.results();
    Iterator iter = res.iterator();
    DefaultTableModel table = (DefaultTableModel) businessesTable.getModel();

    while (iter.hasNext()) {
        DBObject dbo = (DBObject) iter.next();
        table.addRow(
                new Object[] { dbo.get("name"), dbo.get("city"), dbo.get("state"), (double) dbo.get("stars") });
    }

    client.close();
}