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:pa036.sprava_uziv_profilov.nosql.persistence.RestaurantPersistence.java

/**
 * Gets average rating of the selected restaurant
 * @param restaurantId//from   ww  w. j av a 2  s .  c om
 * @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:pt.tiago.mongodbteste.MongoDB.java

private void queries() {

    DBCollection coll = db.getCollection("Purchase");
    //find the sum group by category
    DBObject group = new BasicDBObject("$group",
            new BasicDBObject("_id", "$categoryID").append("total", new BasicDBObject("$sum", "$price")));
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("price", 1));
    AggregationOutput output = coll.aggregate(group, sort);
    for (DBObject result : output.results()) {
        System.out.println(result);
    }//from   w  w w .  ja va 2 s.c  o m

    System.out.println("////////////////////////////////");

    //find the year of date
    //SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase
    // $group : {_id : { year : {$year : "$birth_date"}},  total : {$sum : 1}
    System.out.println("SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase");
    DBCollection collection2 = db.getCollection("Purchase");
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("year", new BasicDBObject("$year", "$dateOfPurchase")))
                    .append("total", new BasicDBObject("$sum", 1)));
    output = collection2.aggregate(group);
    BasicDBObject basicObj;
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        basicObj = (BasicDBObject) basicObj.get("_id");
        System.out.println(basicObj.get("year"));
        ;

    }

    System.out.println("////////////////////////////////");

    //find the sum with year and categoryID
    // SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?
    System.out.println(
            "SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?");
    int year = 2014;
    Calendar cal = Calendar.getInstance();
    cal.set(year, 0, 0);
    Calendar cal2 = Calendar.getInstance();
    cal2.set(year, 11, 31);
    BasicDBObject match = new BasicDBObject("$match",
            new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8")));
    match.put("$match", new BasicDBObject("dateOfPurchase",
            new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime())));
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(match, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.getDouble("total"));
    }

    System.out.println("////////////////////////////////");

    System.out.println("SELECT SUM(Price) , MONTH(DateOfPurchase)"
            + " FROM Purchase WHERE PersonID = ? AND CategoryID = ? "
            + "AND Price <= ? GROUP BY MONTH(DateOfPurchase)");
    coll = db.getCollection("Purchase");
    BasicDBObject cateObj = new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8"));
    BasicDBObject personObj = new BasicDBObject("personID", new ObjectId("548079fa46e68338719aa1f6"));
    BasicDBList and = new BasicDBList();
    and.add(cateObj);
    and.add(personObj);
    DBObject andCriteria = new BasicDBObject("$and", and);
    DBObject matchCriteria = new BasicDBObject("$match", andCriteria);
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price")));
    group.put("$group",
            new BasicDBObject("_id", new BasicDBObject("month", new BasicDBObject("$month", "$dateOfPurchase")))
                    .append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(matchCriteria, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.toString());
    }

    System.out.println("////////////////////////////////");

    System.out.println("SELECT SUM(Price) , PersonID FROM Purchase WHERE  "
            + "YEAR(DateOfPurchase) = ? AND Price <= ? GROUP BY PersonID");
    coll = db.getCollection("Purchase");
    year = 2014;
    cal = Calendar.getInstance();
    cal.set(year, 0, 0);
    cal2 = Calendar.getInstance();
    cal2.set(year, 11, 31);

    BasicDBObject priceObj = new BasicDBObject("price", new BasicDBObject("$lte", 2000));
    BasicDBObject dateObj = new BasicDBObject("dateOfPurchase",
            new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime()));
    and = new BasicDBList();
    and.add(priceObj);
    and.add(dateObj);
    andCriteria = new BasicDBObject("$and", and);
    matchCriteria = new BasicDBObject("$match", andCriteria);
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", "$personID").append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(matchCriteria, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.toString());
    }

}

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);
            }// w  w w . j a v  a2 s  .  c  om

            groupID++;
        }
    }

    mongoClient.close();
    return aps;
}

From source file:utils.ExternalResources.java

public static Map<String, Map<String, DataBag>> getSFtoAvailabilityProfileNames(final String mongoHostname,
        final int port) throws UnknownHostException {
    Map<String, Map<String, DataBag>> poemMap = new HashMap<String, Map<String, DataBag>>(10);
    BagFactory mBagFactory = BagFactory.getInstance();
    TupleFactory mTupleFactory = TupleFactory.getInstance();

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

    // We need to implement this query to get the unique service flavors 
    // for each AP
    // {$project: { name : {$concat : ["$namespace", "-", "$name"]}, groups : 1, poems : 1 }}
    // { $unwind : "$poems" }, {$unwind : "$groups"}, {$unwind : "$groups"},
    // { $group : { _id : {poem : "$poems", sf : "$groups" }, aps : {$addToSet : "$name"}}},
    // { $group : { _id : {poem : "$_id.poem"}, sfs : {$addToSet: { sf : "$_id.sf", aps : "$aps" }}}}
    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));
    DBObject unwindPoems = new BasicDBObject("$unwind", "$poems");
    DBObject unwindGroups = new BasicDBObject("$unwind", "$groups");
    DBObject group = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("poem", "$poems").append("sf", "$groups")).append("aps",
                    new BasicDBObject("$addToSet", "$name")));
    DBObject group2 = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("poem", "$_id.poem")).append("sfs",
                    new BasicDBObject("$addToSet", new BasicDBObject("sf", "$_id.sf").append("aps", "$aps"))));

    AggregationOutput output = collection.aggregate(project, unwindPoems, unwindGroups, unwindGroups, group,
            group2);/*from   www .  ja  v  a 2 s .c  o m*/

    // For each poem profile
    for (DBObject dbo : output.results()) {
        BasicDBList l = (BasicDBList) dbo.get("sfs");
        String poemProfile = (String) ((DBObject) dbo.get("_id")).get("poem");

        Map<String, DataBag> sfMap = new HashMap<String, DataBag>(10);
        // For each service flavour
        for (Object o : l) {
            DBObject sfs = (DBObject) o;

            String serviceFlaver = (String) sfs.get("sf");
            BasicDBList apList = (BasicDBList) sfs.get("aps");

            DataBag apBag = mBagFactory.newDefaultBag();
            // For each AP
            for (Object ap : apList) {
                apBag.add(mTupleFactory.newTuple((String) ap));
            }

            sfMap.put(serviceFlaver, apBag);
        }

        poemMap.put(poemProfile, sfMap);
    }

    mongoClient.close();
    return poemMap;
}

From source file:week1.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");
    }//  ww w  .  j ava  2s.  c o m

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

From source file:week1.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 ww.j  a v  a  2 s  . 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:xbdd.webapp.resource.feature.Report.java

License:Apache License

@GET
@Produces("application/json")
@Path("/tags/{product}/{major}.{minor}.{servicePack}/{build}")
public DBObject getTagList(@BeanParam final Coordinates coordinates) {
    final DB bdd = this.client.getDB("bdd");
    final DBCollection features = bdd.getCollection("features");
    // Build objects for aggregation pipeline
    // id option: returns each tag with a list of associated feature ids
    final DBObject match = new BasicDBObject("$match", coordinates.getReportCoordinatesQueryObject());
    final DBObject fields = new BasicDBObject("tags.name", 1);
    fields.put("_id", 0); // comment out for id option
    final DBObject project = new BasicDBObject("$project", fields);
    final DBObject unwind = new BasicDBObject("$unwind", "$tags");
    final DBObject groupFields = new BasicDBObject("_id", "$tags.name");
    // groupFields.put("features", new BasicDBObject("$addToSet", "$_id")); //comment in for id option
    groupFields.put("amount", new BasicDBObject("$sum", 1));
    final DBObject group = new BasicDBObject("$group", groupFields);
    final DBObject sort = new BasicDBObject("$sort", new BasicDBObject("amount", -1));

    final AggregationOutput output = features.aggregate(match, project, unwind, group, sort);

    // get _ids from each entry of output.result
    final BasicDBList returns = new BasicDBList();
    for (final DBObject obj : output.results()) {
        final String id = obj.get("_id").toString();
        returns.add(id);/*from   w  w  w  .j  av  a  2  s . co  m*/
    }
    return returns;
}

From source file:yelpapp.HW3.java

public SearchResults getUserDetailsQuery(Date y_membersince, String review_condition, String review_value,
        String noofFriends_cond, String nooffriendsvalue, String avgstarscond, String avgstarsVal,
        String maincondition, String userVotesCond, String uservotesValue) {
    SearchResults SearchResults = new SearchResults();

    /*//from w ww . j  av a2  s . c  o m
            
    select y_name,Y_YELPING_SINCE, Y_AVERAGE_STARS
    from y_user_tb yusr 
    where yusr.Y_REVIEW_COUNT = ?
    and yusr.Y_FRIENDS_COUNT = ?
    and yusr.Y_AVERAGE_STARS =?
    */StringBuilder userResultStr = new StringBuilder();
    Connection dbconnection;
    // dbconnection = YelpDBConnectionFactory.connectDatabase();
    DB db1 = new MongoClient("localhost", 27017).getDB("YelpApplication");
    DBCollection dbcollection = db1.getCollection("YelpUser");
    String datestr = "2014-12-09T00:00:00Z";
    if (isdebug)
        System.out.println("start" + " ISODate(" + datestr + ")");

    String query = "";
    List<String> userResults = new ArrayList<String>();
    int count = 0;
    try {

        boolean firstwhereclause = true;
        String mainconditiona = " and ";

        if (isnotnullornotempty(maincondition)) {
            maincondition = maincondition.trim();
            if (isdebug)
                System.out.println("maincondition=" + maincondition);
            if ("and, or".equalsIgnoreCase(maincondition)) {
                maincondition = " and ";
                if (isdebug)
                    System.out.println("maincondition=" + maincondition);
            }
            ;
        }

        else
            maincondition = mainconditiona;

        String option = maincondition.equalsIgnoreCase("and") ? "$and" : "$or";
        DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
        String date_string = df.format(y_membersince);
        if (isdebug)
            System.out.println("date_string + " + date_string + "y_membersince  " + y_membersince);
        BasicDBObject reviewcountcondDBOB = null;
        BasicDBObject reviewcountcond1 = null;
        BasicDBObject yelpingsincecondDBOB = null;
        BasicDBObject yelpingsince = null;
        BasicDBObject friendscondDOB = null;
        BasicDBObject friendsDOB = null;
        BasicDBObject averagestarscondDBOB = null;
        BasicDBObject averagestarscond1 = null;
        BasicDBObject uservotesDOB = null;
        userResultStr = new StringBuilder();
        if (isnotnullornotempty(date_string) && isnotnullornotempty(date_string)) {
            String yelpingcond = "$gt";
            yelpingsincecondDBOB = new BasicDBObject(yelpingcond, y_membersince);
            yelpingsince = new BasicDBObject("yelping_since", yelpingsincecondDBOB);
            if (isdebug)
                System.out.println("yelpingsince  =" + yelpingsince);
        }

        if (isnotnullornotempty(review_value) && isnotnullgezero(review_value)
                && isnotnullornotempty(review_condition)) {

            String reviewcond = condstr(review_condition);
            reviewcountcondDBOB = new BasicDBObject(reviewcond, Integer.parseInt(review_value));
            reviewcountcond1 = new BasicDBObject("review_count", reviewcountcondDBOB);
            System.out.println("Reviw condition =" + reviewcountcond1);

        }

        if (isnotnullornotempty(nooffriendsvalue) && isnotnullgezero(nooffriendsvalue)
                && isnotnullornotempty(noofFriends_cond)) {
            String yelpingcond = condstr(noofFriends_cond);
            friendscondDOB = new BasicDBObject(yelpingcond, Double.parseDouble(nooffriendsvalue));
            friendsDOB = new BasicDBObject("friendsCount", friendscondDOB);
            if (isdebug)
                System.out.println("friendsDOB  =" + friendsDOB);
        }
        if (isnotnullornotempty(userVotesCond) && isnotnullgezero(uservotesValue)
                && isnotnullornotempty(userVotesCond)) {
            String yelpingcond = condstr(userVotesCond);
            friendscondDOB = new BasicDBObject(yelpingcond, Integer.parseInt(uservotesValue));
            uservotesDOB = new BasicDBObject("totalVotes", friendscondDOB);
            //System.out.println("uservotesDOB  ="+uservotesDOB);
        }
        if (isnotnullornotempty(avgstarsVal) && isnotnullgezero(avgstarsVal)
                && isnotnullornotempty(avgstarscond)) {
            String starscond = condstr(avgstarscond);
            averagestarscondDBOB = new BasicDBObject(starscond, Integer.parseInt(avgstarsVal));
            averagestarscond1 = new BasicDBObject("average_stars", averagestarscondDBOB);
            System.out.println("averagestarscond1  =" + averagestarscond1);
        }

        //query to database 

        /* PreparedStatement statement;
            statement = dbconnection.prepareStatement(query);
                    
           ResultSet rs =  statement.executeQuery();
           count=0;
           while(rs.next()) {
               UserDetails useDetails = new  UserDetails();
               useDetails.setYname(rs.getString("y_name"));
               java.util.Date sqlDate;
            sqlDate = new java.util.Date(rs.getDate("Y_YELPING_SINCE").getTime());
             df = new SimpleDateFormat("yyyy-MM");
             df.format(sqlDate);
               useDetails.setYelp_Since(df.format(sqlDate));
                       
               useDetails.setAverage_stars(rs.getString("Y_AVERAGE_STARS"));
                       
               useDetails.setFriends_count(rs.getString("Y_FRIENDS_COUNT"));
           useDetails.setYid(rs.getString("y_id"));
               userResults.add(useDetails);
               count++;
           }*/
        List<BasicDBObject> asList = new ArrayList<BasicDBObject>();
        asList.add(yelpingsince);//reviewcountcond1,averagestarscond1,friendsDOB
        if (null != reviewcountcond1)
            asList.add(reviewcountcond1);
        if (null != averagestarscond1)
            asList.add(averagestarscond1);
        if (null != friendsDOB)
            asList.add(friendsDOB);
        if (null != uservotesDOB)
            asList.add(uservotesDOB);
        DBObject optioncond = new BasicDBObject(option, asList);
        System.out.println("optioncond  =" + optioncond);
        System.out.println("option" + option);
        DBObject match = new BasicDBObject("$match", optioncond);
        System.out.println("match  =" + match);
        DBObject project = new BasicDBObject("$project", new BasicDBObject("name", 1).append("average_stars", 1)
                .append("review_count", 1).append("yelping_since", 1).append("_id", 0));
        DBObject limoit = new BasicDBObject("$limit", 200);
        System.out.println(match);
        AggregationOutput output = dbcollection.aggregate(match, project, limoit);
        System.out.println("output" + output);
        query = match.toString();
        userResults = new ArrayList<String>();
        for (DBObject result : output.results()) {
            System.out.println(result);
            userResults.add(result.toString());
            userResultStr.append(result.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();

    } finally {

    }
    System.out.println(query);
    /*  SearchResults.setIsusersearchResults(true);
      SearchResults.numberofrecords=count;
      SearchResults.setUserSearchresults(userResults);
      SearchResults.Query = query;*/
    System.out.println(query);
    SearchResults.setIsusersearchResults(true);
    SearchResults.numberofrecords = count;
    SearchResults.jason = userResultStr.toString();
    SearchResults.setUserSearchresults(userResults);
    SearchResults.setUserStr(userResults);
    SearchResults.Query = query;
    return SearchResults;
}

From source file:yelpapp.HW3.java

public List getReviewBusiness(Date reviewfrom, Date Reviewto, String Stars_cond, String Stars_value,
        String votes_cond, String votes_value) {
    MongoClient client;//from   w w  w  .j  a va  2  s. c  o  m
    client = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
    DB db1 = new MongoClient("localhost", 27017).getDB("YelpApplication");
    DBCollection dbcollection = db1.getCollection("YelpReview");
    ArrayList businessiidList = null;
    String searchForComboBox = "and";
    BasicDBObject votescountcondDBOB = null;
    BasicDBObject votescountcond1 = null;
    BasicDBObject averagestarscondDBOB = null;
    BasicDBObject averagestarscond1 = null;
    BasicDBObject begincondDBOB = null;
    BasicDBObject rdatecondDBOB = null;
    if (reviewfrom != null && Reviewto != null
            && (!Stars_value.equalsIgnoreCase("0") && !votes_value.equalsIgnoreCase("0"))) {

        DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
        String date_string_reviewfrom = df.format(reviewfrom);
        String date_string_reviewto = df.format(Reviewto);
        String rdatecond = "$gt";
        begincondDBOB = new BasicDBObject("$gt", reviewfrom).append("$lt", Reviewto);//" ISODate("+datestr+")"
        rdatecondDBOB = new BasicDBObject("date", begincondDBOB);
        System.out.println("rdatecondDBOB" + rdatecondDBOB);
        if (!votes_value.equalsIgnoreCase("0")) {

            String reviewcond = condstr(votes_cond);
            votescountcondDBOB = new BasicDBObject(reviewcond, Double.parseDouble(votes_value));
            votescountcond1 = new BasicDBObject("totalVotes", votescountcondDBOB);
        }
        if (!Stars_value.equalsIgnoreCase("0")) {

            String starscond = condstr(Stars_cond);
            averagestarscondDBOB = new BasicDBObject(starscond, Integer.parseInt(Stars_value));
            averagestarscond1 = new BasicDBObject("stars", averagestarscondDBOB);
        }
        String datestr = "2014-12-09T00:00:00Z";
        System.out.println("start" + "new ISODate(" + datestr + ")");
        String option = "$and";

        BasicDBObject proj1 = new BasicDBObject();

        List<BasicDBObject> asList = new ArrayList<BasicDBObject>();
        // asList.add(rdatecondDBOB);//reviewcountcond1,averagestarscond1,friendsDOB
        if (null != averagestarscond1)
            asList.add(averagestarscond1);
        if (null != rdatecondDBOB)
            asList.add(rdatecondDBOB);
        if (null != votescountcond1)
            asList.add(votescountcond1);

        DBObject optioncond = new BasicDBObject(option, asList);
        /*   db.YelpUser.aggregate([
                          { 
                            $match: {
                                 $and: [ 
                                              
                                     {date: {$gt: 3,$lt :5}}, 
                              {stars: {$gt: 3}}, 
                                     {$votes.useful: {$gt:2}},
                                       
                                       
                                 ]
                            }
                          }
                         ])*/

        System.out.println("optioncond  =" + optioncond);
        System.out.println("option" + option);
        DBObject match = new BasicDBObject("$match", optioncond);
        System.out.println("match  =" + match);
        DBObject project = new BasicDBObject("$project", new BasicDBObject("business_id", 1).append("_id", 0));

        System.out.println(match);
        AggregationOutput output = dbcollection.aggregate(match, project);
        System.out.println("output" + output);
        // query = match.toString();
        businessiidList = new ArrayList<String>();
        for (DBObject result : output.results()) {
            System.out.println("reviews" + result);
            businessiidList.add(result.get("business_id"));
            //System.out.println(businessiidList);
        }

    }
    System.out.println("Done executing review");
    return businessiidList;

}

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);/* w  w w.  j  av a 2 s. co  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();
}