Example usage for com.mongodb.client MongoCollection find

List of usage examples for com.mongodb.client MongoCollection find

Introduction

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

Prototype

FindIterable<TDocument> find();

Source Link

Document

Finds all documents in the collection.

Usage

From source file:StartScreen.java

private void insertMongo() throws Exception {
    // *****This is to connect to database**//

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");

    MongoCollection<Document> elexirCollection = db.getCollection("test");

    // *********This is to connect to the database***********//

    //To clear out existing files from mongo
    db.getCollection("test").deleteMany(new Document());

    // *******This is to read the file into program*********//
    //String fileDirectory = chooser.getCurrentDirectory() + "";

    FileReader file = new FileReader(pathField.getText());
    BufferedReader reader = new BufferedReader(file);

    String line = reader.readLine();

    // **********This is to read the text file into program***************//

    // Creating the Array List to store types of variables
    List<String> Types = new ArrayList<String>();
    List<String> Objects = new ArrayList<String>();
    List<String> Predicates = new ArrayList<String>();
    List<String> Cats = new ArrayList<String>();
    List<String> Category = new ArrayList<String>();
    List<String> Action = new ArrayList<String>();

    List<Double> DerivProb = new ArrayList<Double>();
    List<Double> RootProb = new ArrayList<Double>();
    List<String> InitialState = new ArrayList<String>();
    List<String> FinalState = new ArrayList<String>();
    List<String> Roots = new ArrayList<String>();

    List<String> Probability = new ArrayList<String>();

    ArrayList<Document> Doc = new ArrayList<Document>();

    // initialize all types of definitions
    String type = null;//ww w .ja v a 2  s  .c o m
    String object = null;
    String predicate = null;
    String cat = null;
    String category = null;
    String action = null;
    String derivProb = null;
    String rootProb = null;
    String initialState = null;
    String finalState = null;
    String roots = null;
    String probability = null;

    Document Exp = new Document();
    Document definitions = new Document();
    Document stats = new Document();

    // Read type Definitions
    while (line != null) {

        if (line.contains("Defined Type: ")) {
            int startingIndexOfType;
            String types = "Defined Type: ";
            startingIndexOfType = line.indexOf("Defined Type: ");
            int endingIndexOfType = line.indexOf(".");
            type = line.substring(startingIndexOfType + types.length(), endingIndexOfType);
            // putting the piece of string into the new string
            Types.add(type);

        }

        // Read object definitions.
        else if (line.contains("Defined Object: ")) {
            int startingIndexOfObj; // this is to split each word from its
            // spaces and print word by word
            String objects = "Defined Object: ";
            startingIndexOfObj = line.indexOf("Defined Object: ");
            int endingIndexOfObj = line.indexOf(".");
            object = line.substring(startingIndexOfObj + objects.length(), endingIndexOfObj);
            // putting the piece of string into the new string
            Objects.add(object);
        }

        // Read predicate definitions.
        else if (line.contains("Defined predicate:")) {
            String predicates = "Defined predicate:";
            int startingIndexOfPred; // this is to split each word from its
            // spaces and print word by word
            startingIndexOfPred = line.indexOf("Defined predicate:");
            int endingIndexOfPred = line.indexOf(".");
            predicate = line.substring(startingIndexOfPred + predicates.length(), endingIndexOfPred);
            // putting the piece of string into the new string
            Predicates.add(predicate);
        }

        // Defined Cat-Definition
        else if (line.contains("Defined: Cat-Definition: ")) {
            int startingIndexOfCat; // this is to split each word from its
            // spaces and print word by word
            String catDef = "Defined: Cat-Definition: ";
            startingIndexOfCat = line.indexOf("Defined: Cat-Definition: ");
            int endingIndexOfCat = line.indexOf(".", startingIndexOfCat);
            cat = line.substring(startingIndexOfCat + catDef.length(), endingIndexOfCat);
            // putting the piece of string into the new string
            Cats.add(cat);
        }

        // Defined Action Definitions

        else if (line.contains("Defined: category: ")) {
            String categ = "Defined: category: ";
            int startingIndexOfCategory = line.indexOf("Defined: category: ");
            int endingIndexOfCategory = line.indexOf(";", startingIndexOfCategory);
            category = line.substring(startingIndexOfCategory + categ.length(), endingIndexOfCategory);
            Category.add(category);

        }

        else if (line.contains("Defined: ")) {
            // this is to split each word from its
            // spaces and print word by word
            String defined = "Defined: ";
            int startingIndexOfAct = line.indexOf("Defined: ");
            int endingIndexOfAct = line.indexOf(".", startingIndexOfAct);
            action = line.substring(startingIndexOfAct + defined.length(), endingIndexOfAct);
            // putting the piece of string into the new string
            Action.add(action);

        }
        line = reader.readLine();
        definitions = new Document();
        if (line.startsWith("Read goals for query."))
            break;

    }

    definitions.append("Types", Types).append("Objects", Objects).append("Predicates", Predicates)
            .append("Cats", Cats).append("Category", Category).append("Actions", Action);

    elexirCollection.insertOne(definitions);

    while (line != null) {

        DerivProb = new ArrayList<Double>();
        RootProb = new ArrayList<Double>(); // To clear out the array so that
        InitialState = new ArrayList<String>(); // the document does not repeat with
        FinalState = new ArrayList<String>(); // roots from previous explanations
        Roots = new ArrayList<String>();

        if (line.startsWith("[Exp:")) {
            String dp = "derivProb :";
            int startingIndexOfDP;
            startingIndexOfDP = line.indexOf("derivProb: ");
            int endingIndexOfDP = line.indexOf(" root", startingIndexOfDP);
            derivProb = line.substring(startingIndexOfDP + dp.length(), endingIndexOfDP);
            DerivProb.add(Double.parseDouble(derivProb));

            String rp = "rootProb :";
            int startingIndexOfRP;
            startingIndexOfRP = line.indexOf("rootProb: ");
            int endingIndexOfRP = line.indexOf(" Initial", startingIndexOfRP);
            rootProb = line.substring(startingIndexOfRP + rp.length(), endingIndexOfRP);
            RootProb.add(Double.parseDouble(rootProb));

            String is = "Initial State:[ ";
            int startingIndexOfIS;
            startingIndexOfIS = line.indexOf("Initial State:[ ");
            int endingIndexOfIS = line.indexOf(" ]", startingIndexOfIS);
            initialState = line.substring(startingIndexOfIS + is.length(), endingIndexOfIS);
            InitialState.add(initialState);

            String fs = "Final State:[ ";
            int startingIndexOfFS;
            startingIndexOfFS = line.indexOf("Final State:[ ");
            int endingIndexOfFS = line.indexOf(" ]", startingIndexOfFS);
            finalState = line.substring(startingIndexOfFS + fs.length(), endingIndexOfFS); // capture last 
            FinalState.add(finalState);

            String rootStr = "root:[";
            for (int x = line.indexOf(rootStr); x > -1; x = line.indexOf(rootStr, ++x)) {
                int endingIndexOfRoot = line.indexOf("]", x);
                roots = line.substring(x + rootStr.length(), endingIndexOfRoot);

                Roots.add(roots);

            }

            Exp = new Document();
            Exp.append("derivProb", Arrays.asList(derivProb)).append("rootProb", Arrays.asList(rootProb))
                    .append("initialState", Arrays.asList(initialState))
                    .append("finalState", Arrays.asList(finalState)).append("Roots", Roots);

            Doc.add(Exp);
            elexirCollection.insertOne(Exp);

        }

        else if (!line.startsWith("[Exp:")) {
            //System.out.println("At first if else");
            // System.out.println(line);
            if (line.contains("Probabilites:")) {
                //System.out.println("At line equals prob");
                while (!line.contains("*** Done with problem. ***")) {
                    //System.out.println("Reached while loop");
                    //read each line and save here

                    probability += line + "\n";

                    //System.out.println(probability);

                    line = reader.readLine();

                }

                Probability.add(probability);
                stats.append("Probability", Probability);
                elexirCollection.insertOne(stats);
            }

        }

        line = reader.readLine();
    } // end while    

    FindIterable<Document> iter = elexirCollection.find();
    System.out.println("Your Documents have been stored into mongoDB ");

}

From source file:ARS.DBManager.java

public int findAllUsers() {

    int counter = 0;

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("ars");
    MongoCollection collection = db.getCollection("users"); //Choosing the collection to insert

    BasicDBObject query = new BasicDBObject();

    MongoCursor cursor = collection.find().iterator();
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
        counter++;//ww w .j  av  a  2  s  .  co m
    }
    return counter;
}

From source file:bariopendatalab.db.DBAccess.java

public String getMunicipi() throws Exception {
    MongoDatabase database = client.getDatabase(DBNAME);
    MongoCollection<Document> collection = database.getCollection(COLLMUNICIPI);
    FindIterable<Document> documents = collection.find();
    List<Document> list = new ArrayList<>();
    for (Document doc : documents) {
        list.add(doc);/*from   w  w  w. ja v  a2 s  .  c  o m*/
    }
    Document response = new Document();
    response.append("size", list.size());
    response.append("results", list);
    return response.toJson();
}

From source file:booklistmanager.FrontController.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    Connector con = new Connector();
    con.connect();/*from ww w.  jav  a 2  s.  c o  m*/
    MongoCollection<Document> col = con.getData();

    for (Document doc : col.find()) {
        int index = (int) doc.get("bookid");
        String name = (String) doc.get("Name");
        String _for = (String) doc.get("For");
        String author = (String) doc.get("Author(s)");
        Label idLabel = new Label(String.valueOf(index));
        Label nameLabel = new Label(name);
        Label forLabel = new Label(_for);
        Label authLabel = new Label(author);

        Button delbtn = new Button("DELETE");
        delbtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                con.delete("bookid", index);
                changeScene("/fxml/front.fxml");
            }
        });

        Button updatebtn = new Button("UPDATE");
        updatebtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                UpdateController.index = index;
                changeScene("/fxml/update.fxml");
            }
        });

        nameLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                DetailsController.ind = index;
                changeScene("/fxml/details.fxml");
            }
        });

        idLabel.setPrefWidth(90);
        nameLabel.setPrefWidth(105);
        forLabel.setPrefWidth(110);
        authLabel.setPrefWidth(130);

        HBox cont = new HBox();
        cont.setSpacing(20);
        cont.setPadding(new Insets(5, 5, 5, 5));

        cont.getChildren().addAll(idLabel, nameLabel, forLabel, authLabel, delbtn, updatebtn);

        list.getChildren().add(cont);
    }

}

From source file:booklistmanager.TablefrontController.java

public ObservableList<Book> getBook() {
    ObservableList<Book> books = FXCollections.observableArrayList();

    Connector con = new Connector();
    con.connect();/*  w  ww.ja  v  a2 s  .  c  o m*/
    MongoCollection<Document> col = con.getData();
    int sl = 1;
    for (Document d : col.find()) {
        Book b = new Book(d, sl++);
        books.add(b);
    }
    return books;
}

From source file:br.inpe.lac.projetoalunoseorientadoresinpe2016.controller.Controller.java

public String getAllPersons() throws Exception {
    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).build();
    MongoClient mongoClient = new MongoClient(new ServerAddress(), options);
    MongoDatabase my_db = mongoClient.getDatabase("alunos_e_orientadores_inpe");
    MongoCollection<Document> pessoas = my_db.getCollection("pessoas");
    List<Document> list = pessoas.find().into(new ArrayList<Document>());
    return new Gson().toJson(list);
}

From source file:cn.edu.hfut.dmic.webcollector.plugin.mongo.MongoDBManager.java

License:Open Source License

@Override
public void merge() throws Exception {
    MongoCollection crawldb = database.getCollection("crawldb");
    MongoCollection fetch = database.getCollection("fetch");
    MongoCollection link = database.getCollection("link");
    LOG.info("start merge");

    /*?fetch*//*from   w w w .  j ava2 s.  c  o  m*/
    LOG.info("merge fetch database");
    FindIterable<Document> findIte = fetch.find();
    for (Document fetchDoc : findIte) {
        MongoDBUtils.updateOrInsert(crawldb, fetchDoc);
    }
    /*?link*/
    LOG.info("merge link database");
    findIte = link.find();
    for (Document linkDoc : findIte) {
        MongoDBUtils.insertIfNotExists(crawldb, linkDoc);
    }

    LOG.info("end merge");

    fetch.drop();
    LOG.debug("remove fetch database");
    link.drop();
    LOG.debug("remove link database");

}

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

License:Open Source License

/**
 * The main method.// w  w w.  j a v a2  s . 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.server.Controller.java

License:Apache License

private void loadUsers() {
    MongoCollection<Document> users = database.getUserCollection();
    int errorCount = 0;
    int userCount = 0;

    try (MongoCursor<Document> cursor = users.find().iterator()) {
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            final Uuid userID = buildUuid(doc.getInteger("id"));

            if (isIdFree(userID)) {
                String name = doc.getString("name");
                Time creation = Time.fromMs(doc.getLong("creation"));
                final String passHash = doc.getString("passHash");
                final String salt = doc.getString("salt");

                model.add(new User(userID, name, creation, passHash, salt));
                LOG.info("Loaded User: \nid: %s\nname: %s\ncreation: %s\n", userID, name, creation);
                userCount++;/*w w w.  j  a  v a 2s . c o m*/
            } else {
                LOG.info("Loading User failure. ID already in use: " + userID);
                errorCount++;
            }
        }
        LOG.info("Successfully loaded %d users. Failed to load %d users.\n", userCount, errorCount);
    }

}

From source file:codeu.chat.server.Controller.java

License:Apache License

private void loadConversations() {
    MongoCollection<Document> conversations = database.getConversationsCollection();
    int errorCount = 0;
    int convoCount = 0;

    try (MongoCursor<Document> cursor = conversations.find().iterator()) {
        while (cursor.hasNext()) {
            Document doc = cursor.next();

            final Uuid conversationID = buildUuid(doc.getInteger("id"));
            final Uuid ownerID = buildUuid(doc.getInteger("owner"));
            final User foundOwner = model.userById().first(ownerID);

            if (foundOwner != null && isIdFree(conversationID)) {
                String title = doc.getString("title");
                Time creation = Time.fromMs(doc.getLong("creation"));
                String passHash = doc.getString("passHash");
                String salt = doc.getString("salt");

                model.add(new Conversation(conversationID, foundOwner.id, creation, title, passHash, salt));
                LOG.info("Loaded Conversation: \nid: %s\ntitle: %s\nowner: %s\ncreation: %s\n", conversationID,
                        title, foundOwner.name, creation);
                convoCount++;//from  w  w w. j  a  v a 2  s  . c om
            } else {
                LOG.info("Loading Conversation failure. Owner not found or ID already in use: "
                        + conversationID);
                errorCount++;
            }
        }
        LOG.info("Successfully loaded %d conversations. Failed to load %d conversations.\n", convoCount,
                errorCount);
    }

}