Example usage for com.mongodb Block Block

List of usage examples for com.mongodb Block Block

Introduction

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

Prototype

Block

Source Link

Usage

From source file:starsaver.ManageStar.java

private void btn_viewAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_viewAllActionPerformed
    //VIEW ALL DOCUMENTS
    txtArea.setText("");
    FindIterable<Document> iterableStars = db.getCollection("stars").find();
    iterableStars.forEach(new Block<Document>() {
        //@Override
        public void apply(final Document document) {
            txtArea.setLineWrap(true);//from w w  w  . ja v  a2 s  .  co m
            txtArea.append(document.toString() + "\n\n");
            System.out.println(document);
        }
    });
}

From source file:tour.PojoQuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *///from  www .  j  ava  2  s .c  o  m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // create codec registry for POJOs
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);

    // get a handle to the "people" collection
    MongoCollection<Person> collection = database.getCollection("people", Person.class);

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    collection.insertOne(ada);

    // Person will now have an ObjectId
    System.out.println("Mutated Person Model: " + ada);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Person somebody = collection.find().first();
    System.out.println(somebody);

    // now, lets add some more people so we can explore queries and cursors
    List<Person> people = asList(
            new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
            new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
            new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)));

    collection.insertMany(people);
    System.out.println("total # of people " + collection.countDocuments());

    System.out.println("");
    // lets get all the documents in the collection and print them out
    Block<Person> printBlock = new Block<Person>() {
        @Override
        public void apply(final Person person) {
            System.out.println(person);
        }
    };

    collection.find().forEach(printBlock);

    System.out.println("");
    // now use a query to get 1 document out
    somebody = collection.find(eq("address.city", "Wimborne")).first();
    System.out.println(somebody);

    System.out.println("");
    // now lets find every over 30
    collection.find(gt("age", 30)).forEach(printBlock);

    System.out.println("");
    // Update One
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")));

    System.out.println("");
    // Update Many
    UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
    System.out.println(updateResult.getModifiedCount());

    System.out.println("");
    // Replace One
    updateResult = collection.replaceOne(eq("name", "Ada Lovelace"), ada);
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("address.city", "Wimborne"));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
    System.out.println(deleteResult.getDeletedCount());

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}

From source file:yelpapp.HW3.java

public List<String> getBusinessDetails(ArrayList<String> Cat, String checkinfrom, String checkinto,
        String noofcheckin_cond, String noofcheckinvalue, Date reviewfrom, Date Reviewto, String Stars_cond,
        String Stars_value, String votes_cond, String votes_value, String searchForComboBox,
        Boolean isaddressselected, Double longitude, Double latitude, Boolean isproximityset,
        String proximity) {//from  w w w.  j  a v  a  2s .  c  o m
    SearchResults SearchResults = new SearchResults();
    Connection dbconnection;
    dbconnection = YelpDBConnectionFactory.connectDatabase();

    MongoClient client;

    client = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

    // TODO Auto-generated method stub
    MongoCollection<Document> b_collection = client.getDatabase("YelpApplication")
            .getCollection("YelpBusiness");
    ArrayList<String> str = Cat;

    String option;
    if (searchForComboBox == "AND") {
        option = "$all";
    } else {
        option = "$in";
    }
    String query = "";

    FindIterable<Document> resultBussinessid = b_collection
            .find(new Document("categories", new Document(option, str)))
            .projection(fields(include("business_id"), excludeId()));
    MongoCursor<Document> iterator = resultBussinessid.iterator();
    final List<String> categoryBuissnessList = new ArrayList<String>();
    resultBussinessid.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            System.out.println("document" + document);

            //if (document != null)System.out.println(document.toJson().toString().trim());

            JSONParser parser = new JSONParser();
            JSONObject jsonObject;

            try {
                jsonObject = (JSONObject) parser.parse(document.toJson().toString().trim());
                String business_id = (String) jsonObject.get("business_id");
                categoryBuissnessList.add(business_id);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Votes Parsing

        }
    });

    query = query + queryCategoryQuery(str);
    List<String> reviewBuissnessList = null;
    reviewBuissnessList = getReviewBusiness(reviewfrom, Reviewto, Stars_cond, Stars_value, votes_cond,
            votes_value);

    System.out.println("reviewBuissnessList" + reviewBuissnessList);

    List<String> proximityBuissnessList = null;
    if (isaddressselected && isproximityset) {
        System.out.println("proximity" + proximity);
        proximityBuissnessList = proximityQuery(longitude, latitude, Integer.parseInt(proximity));

        System.out.println("proximityBuissnessList" + proximityBuissnessList);
        query = query + proxqueryonly(longitude, latitude, Integer.parseInt(proximity));
    }
    List<String> CheckinBuissnessList = null;
    if (!noofcheckinvalue.equalsIgnoreCase("0")) {

        CheckinBuissnessList = getcheckinbusiness(categoryBuissnessList, Integer.parseInt(checkinfrom),
                Integer.parseInt(checkinto), Integer.parseInt(noofcheckinvalue));

    }
    System.out.println("categoryBuissnessList before merging" + categoryBuissnessList.size() + "    jfcjvkbkk  "
            + searchForComboBox);
    if (reviewBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + reviewBuissnessList.size());
    if (proximityBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + proximityBuissnessList.size());
    if (categoryBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + categoryBuissnessList);
    Set ptempimityBuissnessList = new HashSet<String>();
    if (searchForComboBox.equalsIgnoreCase("or")) {
        //do union
        System.out.println("in if ");
        //col.addAll(otherCol)// for union
        if (reviewBuissnessList != null && !votes_value.equalsIgnoreCase("0"))
            categoryBuissnessList.addAll(reviewBuissnessList);
        if (proximityBuissnessList != null)
            categoryBuissnessList.addAll(proximityBuissnessList);

    } else {
        //intersection
        System.out.println("in else ");

        //col.retainAll(otherCol) // for intersection
        if (reviewBuissnessList != null)
            categoryBuissnessList.retainAll(reviewBuissnessList);
        if (proximityBuissnessList != null)
            categoryBuissnessList.retainAll(proximityBuissnessList);

    }
    if (reviewBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + reviewBuissnessList.size());
    if (proximityBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + proximityBuissnessList.size());
    if (categoryBuissnessList != null)
        System.out.println("categoryBuissnessList before merging" + categoryBuissnessList.size());
    if (categoryBuissnessList != null)
        System.out.println("categoryBuissnessList" + categoryBuissnessList.size());
    System.out.println("categoryBuissnessList" + categoryBuissnessList);

    FindIterable<Document> result = b_collection
            .find(new Document("business_id", new Document(option, categoryBuissnessList)))
            .projection(fields(include("name", "city", "stars", "state"), excludeId())).limit(100);
    /*iterator = result.iterator();
    while(iterator.hasNext()){
      if(isdebug)System.out.println(iterator.next());
    }*/
    final List<String> businesses = new ArrayList<String>();
    result.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            businesses.add(document.toJson().toString().trim());
            System.out.println(document.toJson().toString().trim());
        }
    });

    /*
            
    if( subCat== null || (subCat != null &&subCat.size() == 0) )  {
               
       subCat = getSubcatogeries(Cat);
    }
       System.out.println("got subcat"+subCat);
               
               
     List userResults = new ArrayList();
     int count=0; 
     String query = "";
       try { 
               
       boolean firstwhereclause = true;//+ "      where ";
               
       String  checkinquery ="";
      if(!noofcheckinvalue.equalsIgnoreCase("0")) {
         checkinquery = " SELECT bid   FROM ( SELECT bus.B_BID    AS bid,   SUM(chek.C_COUNT ) AS checkcount   FROM Y_BUSINESS_TB bus JOIN Y_CHECKIN_TB chek  ON chek.C_B_ID =bus.B_BID     JOIN Y_BUS_SUB_CATEGORY subcat      ON bus.B_BID = subcat.B_ID"
            +" WHERE ";
                 
          String cin = formincondition(subCat);
          checkinquery =  checkinquery +" subcat.S_SUB_CAT_NAME  " +cin +"  and chek.C_INFO  between '" +checkinfrom+"' and '"+checkinto+"'  "
       + " group by bus.B_BID)  where checkcount " +noofcheckin_cond+" "+noofcheckinvalue;
                  
                  
      }
              
      String  reviewquery ="";
     if(reviewfrom != null && Reviewto != null && ( !Stars_value.equalsIgnoreCase("0") && !votes_value.equalsIgnoreCase("0")) ) {
         String rin = formincondition(subCat);
        reviewquery = " select bus.B_BID as  bid from Y_BUSINESS_TB bus  join  Y_REVIEWS_TB review on bus.B_BID = review.R_BUSS_ID "
            + "join Y_BUS_SUB_CATEGORY subcat on bus.B_BID = subcat.B_ID where subcat.S_SUB_CAT_NAME " +rin+ " ";
             
          DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
            String date_string_reviewfrom = df.format(reviewfrom);  
            String date_string_reviewto = df.format(Reviewto);  
                    
        reviewquery = reviewquery+" and review.R_PUBLISH_DATE BETWEEN '"+date_string_reviewfrom+"' and '"+date_string_reviewto+"' ";
        if ( !votes_value.equalsIgnoreCase("0") ) {
            
           reviewquery = reviewquery+ " and review.R_VOTES " +votes_cond+ "  '" + votes_value+"' " ;
                   
        }
        if (  !Stars_value.equalsIgnoreCase("0")) {
                   
           reviewquery = reviewquery+ " and  review.r_stars "+ Stars_cond+" '"+Stars_value+"'      ";
        }
                 
                 
     }
     query = " "
           + ""
           + "select B_BID,B_NAME,B_CITY,B_STATE,B_STARS from Y_BUSINESS_TB ab where ab.B_BID in (";
     System.out.println("reviewquery "+reviewquery.equalsIgnoreCase("")+" reviewquery");
     System.out.println("checkinquery "+checkinquery.equalsIgnoreCase("")+" checkinquery.equalsIgnoreCase(");
             
             
      if (reviewquery.equalsIgnoreCase("") && checkinquery.equalsIgnoreCase("")) 
     {
                
         System.out.println("reviewquerasdasdy"+reviewquery+"reviewquery");
        String subcatonly = " select B_ID from Y_BUS_SUB_CATEGORY  where S_SUB_CAT_NAME ";
        String subcatin = formincondition(subCat);
        subcatonly =subcatonly+subcatin;
        query=query+subcatonly + " ) ";
     }
             
      else {      if (reviewquery.equalsIgnoreCase("")){
                
            query = query+checkinquery+ " ) ";
      }
      else if (checkinquery.equalsIgnoreCase("")){
                
            query = query+reviewquery+ " ) ";
      }
             
      else {
         query = query+checkinquery+ " INTERSECT "+reviewquery+ " ) ";
      }
               
      }
               
                
          System.out.println("query"+query);
                  
          }catch (Exception e){
                
            e.printStackTrace();
        }
      //   System.out.println(query);
      //   SearchResults.setIsusersearchResults(true);
      //   SearchResults.numberofrecords=count;
      //   SearchResults.setUserSearchresults(userResults);
      //   SearchResults.Query = query;
    */ return businesses;
}

From source file:yelpapp.HW3.java

private List<String> getcheckinbusiness(List businessids, Integer fromdate, Integer todate,
        Integer keyedin_count) {/*from www  . j  av a  2 s.  c  om*/
    System.out.println("checkinSEARCH ");

    MongoClient client;
    String searchForComboBox = "and";
    System.out.println(businessids);
    DB db1 = new MongoClient("localhost", 27017).getDB("YelpApplication");
    DBCollection dbcollection = db1.getCollection("YelpCheckin");
    List<String> cbeckinBusinessList = null;
    client = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
    /*   System.out.println(asList(match(eq("name", "Tyler")), 
     lookup("YelpReview", "business_id", "business_id", "YelpBusinessReviews"), 
     unwind("$YelpBusinessReviews"),
             
     project(fields(computed("date", "$YelpBusinessReviews.date"), computed("stars", "$YelpBusinessReviews.stars"), computed("text", "$YelpBusinessReviews.text"), computed("userName", "name"), computed("usefulVotes", "votes.useful"),  excludeId())),
     unwind("$userName")));*/
    MongoCollection<Document> b_collection = client.getDatabase("YelpApplication").getCollection("YelpCheckin");
    /*   db.YelpUser.aggregate([
                          { 
                            $match: {
                                 $and: [ 
                                     { business_id: { $in: [ 5, 15 ] } }
                                     {date: {$gt: 3,$lt :5}}, 
                              {stars: {$gt: 3}}, 
                                     {$votes.useful: {$gt:2}},
                                       
                                       
                                 ]
                            }
                          }
                         ])*/

    FindIterable<Document> result = b_collection
            .find(new Document("business_id", new Document("$in", businessids)))
            .projection(fields(include("business_id", "checkin_info"), excludeId()));
    System.out.println("   asdas =" + result);
    MongoCursor<Document> iterator = result.iterator();

    final List<String> checkinJson = new ArrayList<String>();
    result.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            // TODO Auto-generated method stub
            checkinJson.add(document.toJson().toString().trim());
            if (isdebug)
                System.out.println(document.toJson().toString().trim());
        }
    });
    System.out.println("" + checkinJson);

    //got jasonobjects
    try {
        Iterator<String> iterator2 = checkinJson.iterator();
        HashMap<String, Integer> cbeckincountmap = new HashMap<String, Integer>();
        while (iterator2.hasNext()) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObject;

            jsonObject = (JSONObject) parser.parse(iterator2.next());

            //Votes Parsing
            String business_id = (String) jsonObject.get("business_id");

            JSONObject checkininfo = (JSONObject) jsonObject.get("checkin_info");
            String[][] checkin = new String[24][7];
            String[][] checkinT = new String[7][24];
            int checkincount = 0;
            String c_info = null;
            for (int i = 0; i < 24; i++) {
                for (int j = 0; j < 7; j++) {
                    checkin[i][j] = getcheckininfo(checkininfo, i + "-" + j);
                    c_info = getcheckininfo(checkininfo, i + "-" + j);

                    if (c_info != null) {

                        String dayhour = (i >= 10) ? "" + j + i : j + "0" + i;
                        Integer dayhourInt = Integer.parseInt(dayhour);
                        Integer c_infoInt = Integer.parseInt(c_info);
                        /* p_statement.setNString(2, dayhour);
                         p_statement.setNString(3, c_info);//count
                        */

                        if (dayhourInt > fromdate && dayhourInt < todate) {
                            Integer ccount = cbeckincountmap.get(business_id);
                            if (ccount != null) {
                                Integer existing_value = cbeckincountmap.get(business_id);
                                cbeckincountmap.put(business_id, existing_value + c_infoInt);

                            } else {

                                cbeckincountmap.put(business_id, c_infoInt);

                            }
                        }

                        checkincount++;

                        //make changes  to checkin to hold day and then hours
                        // also store the count.

                        //System.out.println(" i = "+i +"J = "+j + "Value "+c_info);
                    }

                    //System.out.println("checkin [][]= "+i+" "+j+" "+checkin[i][j]);
                }
            }
            //System.out.println("checkin [][]= "+checkin);

            // checkinT = ParseJson.transpose(checkin);

            //            
            //              count++;
            //              System.out.println(count+"\n");
        }

        System.out.println("cbeckincountmap" + cbeckincountmap);
        cbeckincountmap.keySet();
        cbeckinBusinessList = new ArrayList<String>();
        Integer count;
        for (String string : cbeckincountmap.keySet()) {
            count = cbeckincountmap.get(string);
            if (count > keyedin_count) {
                cbeckinBusinessList.add(string);
            }
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Done executing checkin");
    return cbeckinBusinessList;
}

From source file:yelp_mongo.Dbconnection.java

public Connection getconnection() {

    Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
    mongoLogger.setLevel(Level.SEVERE);
    // To connect to mongodb server
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    MongoDatabase db = mongoClient.getDatabase("mydb");
    System.out.println("Connect to database successfully");
    //boolean auth = db.authenticate("","");
    //System.out.println("Authentication: "+auth);
    MongoCollection<Document> coll = db.getCollection("yelp");

    System.out.println("Collection yelp selected successfully");

    /*FindIterable<Document> cursor = coll.find();
                 // w  w  w  .j av  a 2s .c om
         cursor.forEach(new Block<Document>() {
         @Override
         public void apply(final Document document) {
             System.out.println(document);
         }
     });*/
    BasicDBObject clause1 = new BasicDBObject("yelping_since", "2012-02");
    //clause1.put("yelping_since", "2012-02");

    BasicDBObject clause2 = new BasicDBObject("review_count", new BasicDBObject("$gt", 500));
    BasicDBObject clause3 = new BasicDBObject("fans", new BasicDBObject("$gt", 15));
    BasicDBObject clause4 = new BasicDBObject("average_stars", new BasicDBObject("$gt", 3));
    //BasicDBObject cl5 = new BasicDBObject("$exist",true);
    //BasicDBObject cl6 = new BasicDBObject("$where","this.friends.length>49");
    //String cl = cl5.toString();
    //BasicDBObject c = new BasicDBObject(cl,cl6);
    //BasicDBObject f = new BasicDBObject("friends",new BasicDBObject("$exist",true));
    BasicDBObject clause5 = new BasicDBObject("friends.50", new BasicDBObject("$exists", true));
    //BasicDBObject cl5 = new BasicDBObject("$where","this.friends.length>3");

    /*BasicDBList fl = new BasicDBList();
    fl.add(f);
    fl.add(cl6);*/

    //clause2.put("review_count",gtquery);
    BasicDBList or = new BasicDBList();

    or.add(clause1);
    or.add(clause2);
    or.add(clause3);
    or.add(clause4);
    or.add(clause5);
    //or.add(fl);

    //fields.put("name",1);
    //fields.put("average_stars",1);
    //fields.put("fans",1);
    BasicDBObject query = new BasicDBObject("$and", or);

    FindIterable<Document> cursor = coll.find(query);
    System.out.println(query);
    cursor.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.get("user_id"));
            System.out.println(document.get("name"));
            System.out.println(document.get("fans"));
            System.out.println(document.get("average_stars"));
            System.out.println(document.get("friends"));

        }
    });

    mongoClient.close();
    System.out.println("Connection successfully closed");

    return null;

}