Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient() 

Source Link

Document

Creates an instance based on a (single) mongodb node (localhost, default port).

Usage

From source file:cl.diinf.sdmongo.Principal.java

public static void main(String[] args) {

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("test");
    FindIterable<Document> iterable = db.getCollection("restaurants").find();

    iterable.forEach(new Block<Document>() {
        @Override/*w w w. jav  a 2 s. c  o m*/
        public void apply(final Document document) {
            System.out.println(document);
        }
    });

    System.out.println("Hola mundo");
}

From source file:cl.wsconsulta.consulta.Consulta.java

@WebMethod(operationName = "consultar")
public String realizarConsulta(@WebParam(name = "consulta") BasicDBList privileges) throws IOException {
    DB database;//from w  w  w  .  j  a  v a  2s.  co  m
    try (BufferedReader entrada = new BufferedReader(new FileReader("datos.ini"))) {
        database = null;
        try {
            dataBase = entrada.readLine();
            indiceInvertido = entrada.readLine();
            coleccionDocumentos = entrada.readLine();
            coleccionIndice = entrada.readLine();

            MongoClient mongoClient = new MongoClient();
            database = mongoClient.getDB(dataBase);

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        entrada.close();
    }

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);

    while (true) {

        BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
        String consulta = lector.readLine().toUpperCase();
        BasicDBObject query = new BasicDBObject("palabra", consulta);
        DBCursor cursor = indiceInvertido.find(query);
        if (cursor.count() == 0) {
            System.out.println("Busqueda sin resultados: " + consulta);
        } else {
            while (cursor.hasNext()) {
                privileges = (BasicDBList) cursor.next().get("documento");
                //DBObject obj = cursor.next();
                //Object value = obj.get("documento");
                //System.out.println(value);
            }
            System.out.println(privileges);
        }
    }

}

From source file:cl.wsconsulta.servlet.ConsultaServlet.java

public static String consultar(String consulta) throws FileNotFoundException, IOException {

    DB database;/*from w  w w. j  a v  a2  s .c o m*/

    database = null;

    dataBase = "labsd";
    indiceInvertido = "prueba.xml";
    coleccionDocumentos = "documentos";
    coleccionIndice = "indiceInvertido";

    MongoClient mongoClient = new MongoClient();
    database = mongoClient.getDB(dataBase);

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);
    BasicDBList privileges = new BasicDBList();

    BasicDBObject query = new BasicDBObject("palabra", consulta);
    DBCursor cursor = indiceInvertido.find(query);
    if (cursor.count() == 0) {
        System.out.println("Busqueda sin resultados: " + consulta);
    } else {
        while (cursor.hasNext()) {

            privileges = (BasicDBList) cursor.next().get("documento");

            //DBObject obj = cursor.next();
            //Object value = obj.get("documento");
            //System.out.println(value);
        }
    }
    String lista = privileges.toString();
    return lista;

}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java

License:Open Source License

/**
 * The main method.//  w  w w . ja va 2 s  . c o m
 *
 * @param args
 *            the arguments
 */
public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase numbersDB = client.getDatabase("students");
    MongoCollection<Document> grades = numbersDB.getCollection("grades");

    // Gets all the grades.
    MongoCursor<Document> cursor = grades.find(Filters.eq("type", "homework"))
            .sort(Sorts.ascending("student_id", "score")).iterator();

    Object previousStudentId = null;
    try {
        // Finds the lowest homework score.
        while (cursor.hasNext()) {
            Document entry = cursor.next();

            // If the student_id is different from the previous one, this 
            // means that this is the student's lowest graded homework 
            // (they are sorted by score for each student).
            if (!entry.get("student_id").equals(previousStudentId)) {
                Object id = entry.get("_id");
                grades.deleteOne(Filters.eq("_id", id));

            }

            // The current document ID becomes the new previous one.   
            previousStudentId = entry.get("student_id");
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = grades
                .aggregate(Arrays.asList(Aggregates.group("$student_id", Accumulators.avg("average", "$score")),
                        Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework31.MainClass.java

License:Open Source License

/**
 * The main method./*w  w w .j av a2s . co m*/
 *
 * @param args
 *            the arguments
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("school");
    MongoCollection<Document> students = db.getCollection("students");

    // Gets all the students.
    MongoCursor<Document> cursor = students.find().iterator();

    try {
        while (cursor.hasNext()) {
            Document student = cursor.next();
            List<Document> scores = (List<Document>) student.get("scores");

            // Finds the lowest homework score.
            Document minScoreObj = null;
            double minScore = Double.MAX_VALUE;

            for (Document scoreDocument : scores) {
                double score = scoreDocument.getDouble("score");
                String type = scoreDocument.getString("type");

                // Swaps the scores.
                if (type.equals("homework") && score < minScore) {
                    minScore = score;
                    minScoreObj = scoreDocument;
                }
            }

            // Removes the lowest score.
            if (minScoreObj != null) {
                scores.remove(minScoreObj);
            }

            // Updates the record.
            students.updateOne(Filters.eq("_id", student.get("_id")),
                    new Document("$set", new Document("scores", scores)));
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = students.aggregate(Arrays.asList(Aggregates.unwind("$scores"),
                Aggregates.group("$_id", Accumulators.avg("average", "$scores.score")),
                Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:codeu.chat.database.Database.java

License:Apache License

public Database(String path) {
    //silence console output
    Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);

    mongoClient = new MongoClient();
    database = mongoClient.getDatabase(path);

    users = database.getCollection("users");
    messages = database.getCollection("messages");
    conversations = database.getCollection("conversations");
}

From source file:com.abhishek.mongodb.homework.week2.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/week2freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override// ww  w.  j  a  v  a  2s  .  c om
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = 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
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.AlertMailerWebPage.servlet.GetDaily.java

public AggregateIterable<Document> getCounts(String database, String collection, String serverAddress) {

    Calendar current = Calendar.getInstance();

    int currYear = current.get(Calendar.YEAR);
    int currMonth = current.get(Calendar.MONTH);
    int currDay = current.get(Calendar.DAY_OF_MONTH);
    currMonth = 6;//from w w  w.  ja v a  2 s. c  o m
    currDay = 4;

    Calendar curr_6AM = Calendar.getInstance();
    curr_6AM.set(currYear, currMonth, currDay, 0, 0, 0);
    curr_6AM.set(Calendar.MILLISECOND, 0);
    // out.println(curr_6AM.getTimeInMillis());

    //MongoClient mongoClient = new MongoClient(new ServerAddress(serverAddress,27017));

    MongoClient mongoClient = new MongoClient();

    //MongoClient mongoClient = new MongoClient();
    AggregateIterable<Document> iterable_6_9_p = mongoClient.getDatabase(database).getCollection(collection)
            .aggregate(asList(new Document("$match", new Document("sentDate", curr_6AM.getTimeInMillis())
                    //.append("alertType", alertType)
                    .append("isMailSent", "Y")
    //.append("recordTime", new Document("$gte",curr_6AM.getTimeInMillis()).append("$lte", curr_9AM.getTimeInMillis()))
    ), new Document("$group",
            new Document("_id", new Document("hour", "$sentHour").append("type", "$alertType")).append("count",
                    new Document("$sum", 1)))));
    //mongoClient.close();
    return iterable_6_9_p;
}

From source file:com.AlertMailerWebPage.servlet.GetDailyOpenMail.java

public AggregateIterable<Document> getCounts(String database, String collection, String serverAddress) {

    Calendar current = Calendar.getInstance();

    int currYear = current.get(Calendar.YEAR);
    int currMonth = current.get(Calendar.MONTH);
    currMonth = 4;//from  ww w . j  a v  a  2 s. c om
    currYear = 2015;
    int currDay = current.get(Calendar.DAY_OF_MONTH);

    Calendar curr_6AM = Calendar.getInstance();
    curr_6AM.set(currYear, currMonth, 18, 0, 0, 0);
    curr_6AM.set(Calendar.MILLISECOND, 0);
    // out.println(curr_6AM.getTimeInMillis());

    // MongoClient mongoClient = new MongoClient(new ServerAddress(serverAddress,27017));
    MongoClient mongoClient = new MongoClient();
    // MongoClient mongoClient = new MongoClient();
    AggregateIterable<Document> iterable_6_9_p = mongoClient.getDatabase(database).getCollection(collection)
            .aggregate(asList(new Document("$match", new Document("openDate", curr_6AM.getTimeInMillis())
    //.append("openDate",curr_6AM.getTimeInMillis())                

    //.append("recordTime", new Document("$gte",curr_6AM.getTimeInMillis()).append("$lt", curr_9AM.getTimeInMillis()))
    ), new Document("$group",
            new Document("_id", new Document("hour", "$openHour").append("type", "$alertType")).append("count",
                    new Document("$sum", 1)))));

    return iterable_6_9_p;
}

From source file:com.AlertMailerWebPage.servlet.GetDailyPRSProcessStats.java

public AggregateIterable<Document> getCounts(String database, String collection, String serverAddress,
        String time) {/*  www.  j a v a 2  s. com*/
    Calendar current = Calendar.getInstance();
    //out.println( current.getTimeInMillis());
    int currYear = current.get(Calendar.YEAR);
    int currMonth = current.get(Calendar.MONTH);
    //currMonth=6;
    int currDay = current.get(Calendar.DAY_OF_MONTH);

    list.clear();

    Calendar curr_6AM = Calendar.getInstance();
    Calendar curr_24PM = Calendar.getInstance();
    if (time.equals("daily")) {
        //Calendar curr_6AM=Calendar.getInstance();
        curr_6AM.set(currYear, 6, 7, 0, 0, 1);
        // out.println(curr_6AM.getTimeInMillis());

        //Calendar curr_24PM=Calendar.getInstance();
        curr_24PM.set(currYear, 6, 7, 23, 59, 59);
        //out.println(curr_9AM.getTimeInMillis());
    } else if (time.equals("weekly")) {

        curr_6AM.set(currYear, 6, 7, 0, 0, 1);
        curr_6AM.add(Calendar.DATE, -6);

        curr_24PM.set(currYear, 6, 7, 23, 59, 59);
    } else if (time.equals("monthly")) {

        curr_6AM.set(currYear, 6, 7, 0, 0, 1);
        curr_6AM.add(Calendar.DATE, -29);

        curr_24PM.set(currYear, 6, 7, 23, 59, 59);
    }

    //MongoClient mongoClient = new MongoClient(new ServerAddress(serverAddress,27017));
    MongoClient mongoClient = new MongoClient();
    //MongoClient mongoClient = new MongoClient();
    AggregateIterable<Document> iterable_6_9_p = mongoClient.getDatabase(database).getCollection(collection)
            .aggregate(asList(new Document("$match",
                    new Document("date", new Document("$gte", Long.toString(curr_6AM.getTimeInMillis()))
                            .append("$lte", Long.toString(curr_24PM.getTimeInMillis())))
    //.append("alertType", alertType)                
    //.append("date", new Document("$gte",Long.toString(curr_6AM.getTimeInMillis())).append("$lt", Long.toString(curr_24PM.getTimeInMillis())))
    ),

                    new Document("$group",
                            new Document("_id", "$errorCode").append("count", new Document("$sum", 1)))));

    return iterable_6_9_p;
}