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(ClientSession clientSession);

Source Link

Document

Finds all documents in the collection.

Usage

From source file:org.mongodb.tse.tests.RunQueryThreadPool.java

public static void main(String[] args) {
    Option help = Option.builder("help").argName("help").desc("get help").build();
    Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class)
            .build();/*w  ww  .j a v  a  2s . co m*/
    Option odatabase = Option.builder("database").argName("database")
            .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build();
    Option ocollection = Option.builder("collection").argName("collection")
            .desc("mongodb collection, default product").hasArg().type(String.class).build();
    Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds")
            .hasArg().type(Integer.class).build();
    Option othreads = Option.builder("threads").argName("threads").desc("number of threads to run, default 5")
            .hasArg().type(Integer.class).build();
    Option readPreference = Option.builder("readPreference").argName("readPreference")
            .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build();
    Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg()
            .type(String.class).build();
    Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg()
            .type(String.class).build();
    Option oincludeslow = Option.builder("includeslow").argName("includeslow")
            .desc("run slow query that will pause 1 second for every document in collection").build();
    Option oincreasethreads = Option.builder("increasethreads").argName("increasethreads")
            .desc("increase thread count every second until this number").hasArg().type(Integer.class).build();

    Options options = new Options();
    options.addOption(help);
    options.addOption(ouri);
    options.addOption(odatabase);
    options.addOption(ocollection);
    options.addOption(osleep);
    options.addOption(othreads);
    options.addOption(readPreference);
    options.addOption(oids);
    options.addOption(oidFile);
    options.addOption(oincludeslow);
    options.addOption(oincreasethreads);

    CommandLineParser parser = new DefaultParser();
    CommandLine cline = null;
    try {
        // parse the command line arguments
        cline = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) {
        printHelp(options);
    }

    final String[] ids = parseIdFile(cline);

    String uriParameter = cline.getOptionValue("uri");
    String databaseParameter = cline.getOptionValue("database", "productpersistdb");
    String collectionParameter = cline.getOptionValue("collection", "product");
    System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter);

    MongoClientURI uri = new MongoClientURI(uriParameter);
    MongoClient mongoClient = new MongoClient(uri);

    MongoDatabase database = mongoClient.getDatabase(databaseParameter);
    final MongoCollection<Document> collection = getCollection(cline, database, collectionParameter);

    long tsleep = 10000;
    if (cline.hasOption("sleep"))
        tsleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000;
    final long sleep = tsleep;
    int threads = 5;
    if (cline.hasOption("threads"))
        threads = Integer.parseInt(cline.getOptionValue("threads"));

    int max = ids.length;
    boolean includeslow = cline.hasOption("includeslow");
    ExecutorService pool = Executors.newCachedThreadPool();
    for (int i = 0; i < threads; i++) {
        pool.execute(new Runnable() {
            public void run() {
                int count = 0;
                for (;;) {
                    String id = ids[(count % max)];
                    Document doc = null;
                    RawBsonDocument raw = null;

                    Date date = new Date();
                    long end = 0L;
                    long start = System.nanoTime();

                    try {
                        if (includeslow
                        //&& ( count % 2 ) == 0 
                        ) {
                            FindIterable<Document> fit = collection
                                    .find(where("function() { "
                                            + "var d = new Date((new Date()).getTime() + 1*1000); "
                                            + "while ( d > (new Date())) { }; " + "return true;" + "}"))
                                    .limit(100);
                            int dcount = 0;
                            for (Document d : fit) {
                                dcount++;
                            }
                            System.out.println(
                                    String.format("%s - slow query, count:%s, start: %s, elasped: %s ns",
                                            Thread.currentThread().getName(), dcount, date, (end - start)));
                        } else {
                            doc = collection
                                    .find(and(eq("_id", id), where("function() { "
                                            + "var d = new Date((new Date()).getTime() + 1*1000); "
                                            + "while ( d > (new Date())) { }; " + "return true;" + "}")))
                                    .first();
                            end = System.nanoTime();
                            if (doc == null)
                                System.out.println("Could not find " + id);
                            System.out.println(String.format("%s - id: %s, start: %s, elasped: %s ns",
                                    Thread.currentThread().getName(), id, date, (end - start)));
                        }
                    } catch (Exception e) {
                        System.out.println("Got an exception: " + e.getMessage());
                        e.printStackTrace();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e2) {
                        }
                    }

                    //try { Thread.sleep(sleep); } catch ( InterruptedException e ) {}
                    count++;

                }

            }
        });
    }
    if (cline.hasOption("increasethreads")) {
        int increaseThreads = Integer.parseInt(cline.getOptionValue("increasethreads"));
        for (int i = threads; i < increaseThreads; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            pool.execute(new Runnable() {
                public void run() {
                    int count = 0;
                    for (;;) {
                        String id = ids[(count % max)];
                        Document doc = null;
                        RawBsonDocument raw = null;

                        Date date = new Date();
                        long end = 0L;
                        long start = System.nanoTime();

                        try {
                            if (includeslow
                            //&& ( count % 2 == 0 ) 
                            ) {
                                FindIterable<Document> fit = collection
                                        .find(where("function() { "
                                                + "var d = new Date((new Date()).getTime() + 1*1000); "
                                                + "while ( d > (new Date())) { }; " + "return true;" + "}"))
                                        .limit(100);
                                int dcount = 0;
                                for (Document d : fit) {
                                    dcount++;
                                }
                                System.out.println(
                                        String.format("%s - slow query, count:%s, start: %s, elasped: %s ns",
                                                Thread.currentThread().getName(), dcount, date, (end - start)));
                            } else {
                                doc = collection
                                        .find(and(eq("_id", id), where("function() { "
                                                + "var d = new Date((new Date()).getTime() + 1*1000); "
                                                + "while ( d > (new Date())) { }; " + "return true;" + "}")))
                                        .first();
                                end = System.nanoTime();
                                if (doc == null)
                                    System.out.println("Could not find " + id);
                                System.out.println(String.format("%s - id: %s, start: %s, elasped: %s ns",
                                        Thread.currentThread().getName(), id, date, (end - start)));
                            }
                        } catch (Exception e) {
                            System.out.println("Got an exception: " + e.getMessage());
                            e.printStackTrace();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e2) {
                            }
                        }

                        //try { Thread.sleep(sleep); } catch ( InterruptedException e ) {}
                        count++;

                    }

                }
            });
        }
    }
}

From source file:org.mongodb.tse.tests.Timings.java

public static void main(String[] args) throws ParseException {

    Option help = Option.builder("help").argName("help").desc("get help").build();
    Option test = Option.builder("test").argName("test").desc("quick test").build();
    Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class)
            .build();//from ww w  . jav  a  2s  .c om
    Option odatabase = Option.builder("database").argName("database")
            .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build();
    Option ocollection = Option.builder("collection").argName("collection")
            .desc("mongodb collection, default product").hasArg().type(String.class).build();
    Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds")
            .hasArg().type(Integer.class).build();
    Option otimes = Option.builder("times").argName("times").desc("number of times to run, default 100")
            .hasArg().type(Integer.class).build();
    Option readPreference = Option.builder("readPreference").argName("readPreference")
            .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build();
    Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg()
            .type(String.class).build();
    Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg()
            .type(String.class).build();
    Option odoc = Option.builder("doc").argName("doc")
            .desc("get a Document instead of RawBsonDocument, no size output with this option").build();

    Options options = new Options();
    options.addOption(help);
    options.addOption(test);
    options.addOption(ouri);
    options.addOption(odatabase);
    options.addOption(ocollection);
    options.addOption(osleep);
    options.addOption(otimes);
    options.addOption(readPreference);
    options.addOption(oids);
    options.addOption(oidFile);
    options.addOption(odoc);

    CommandLineParser parser = new DefaultParser();
    CommandLine cline = null;
    try {
        // parse the command line arguments
        cline = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) {
        printHelp(options);
    }

    if (cline.hasOption("test")) {
        List<Double> testList = new ArrayList<Double>();
        for (int i = 0; i < 100; i++) {
            testList.add(new Double(i));
        }
        Collections.sort(testList);
        System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
                percentile(testList, 0.50), percentile(testList, 0.75), percentile(testList, 0.90),
                percentile(testList, 0.95), percentile(testList, 0.99)));
        System.exit(0);
    }

    String[] ids = null;
    if (cline.hasOption("idFile")) {
        ids = parseIdFile(new File(cline.getOptionValue("idFile")));
    } else
        ids = cline.getOptionValue("ids", "517886481000").split(",");

    List<Double> timeList = new ArrayList<>();

    String uriParameter = cline.getOptionValue("uri");
    String databaseParameter = cline.getOptionValue("database", "productpersistdb");
    String collectionParameter = cline.getOptionValue("collection", "product");
    System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter);

    MongoClientURI uri = new MongoClientURI(uriParameter);
    MongoClient mongoClient = new MongoClient(uri);

    MongoDatabase database = mongoClient.getDatabase(databaseParameter);
    MongoCollection<Document> collection = null;
    MongoCollection<RawBsonDocument> rawCollection = null;

    boolean doDoc = cline.hasOption("doc");
    if (doDoc) {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    } else {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    }

    long sleep = 10000;
    if (cline.hasOption("sleep"))
        sleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000;
    int times = 100;
    if (cline.hasOption("times"))
        times = Integer.parseInt(cline.getOptionValue("times"));

    int count = 0;
    int max = ids.length;
    while (count < times) {
        String id = ids[(count % max)];
        Document doc = null;
        RawBsonDocument raw = null;

        Date date = new Date();
        long end = 0L;
        long start = System.nanoTime();
        if (doDoc) {
            doc = collection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (doc == null)
                System.out.println("Could not find " + id);
        } else {
            raw = rawCollection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (raw == null)
                System.out.println("Could not find " + id);
        }

        int size = 0;
        if (raw != null)
            size = raw.getByteBuffer().capacity();

        if (raw != null) {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns, docSize: %s", id, date,
                    (end - start), size));
        } else {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns", id, date, (end - start)));
        }
        timeList.add(new Double(end - start));
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
        }
        count++;
    }

    Collections.sort(timeList);

    System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
            percentile(timeList, 0.50), percentile(timeList, 0.75), percentile(timeList, 0.90),
            percentile(timeList, 0.95), percentile(timeList, 0.99)));
}

From source file:org.mongojx.fluent.JxFindIterable.java

License:Apache License

public JxFindIterable(ObjectMapper mapper, MongoCollection collection, String filter, Object... parameters) {
    this.mapper = mapper;
    findIterable = collection.find(MongoJxParser.bind(filter, parameters).getDocuments().get(0));
}

From source file:org.nuxeo.tools.esync.db.DbMongo.java

License:Open Source License

@Override
public List<Document> getDocumentWithAcl() {
    final List<Document> ret = new ArrayList<>();
    MongoCollection<org.bson.Document> table = getMongoCollection();
    BasicDBObject searchQuery = new BasicDBObject("ecm:acp", new BasicDBObject("$exists", true));
    FindIterable<org.bson.Document> iterable = table.find(searchQuery);
    iterable.forEach(new Block<org.bson.Document>() {
        @Override/*from w w w  .  ja  v  a2s .c  o m*/
        public void apply(final org.bson.Document document) {
            ArrayList<String> racl = document.get("ecm:racl", ArrayList.class);
            String[] acl = racl.toArray(new String[racl.size()]);
            Document doc = new Document(document.getString("ecm:id"), document.getString("ecm:primaryType"),
                    acl);
            ret.add(doc);
        }
    });
    return ret;
}

From source file:org.nuxeo.tools.esync.db.DbMongo.java

License:Open Source License

private void findAndDump(BasicDBObject searchQuery) {
    MongoCollection<org.bson.Document> table = getMongoCollection();
    FindIterable<org.bson.Document> iterable = table.find(searchQuery);
    iterable.forEach(new Block<org.bson.Document>() {
        @Override/*from w w w .j av a 2 s .  co  m*/
        public void apply(final org.bson.Document document) {
            System.out.println(document);
        }
    });
}

From source file:org.nuxeo.tools.esync.db.DbMongo.java

License:Open Source License

@Override
public Document getDocument(String id) {
    final Document[] ret = new Document[1];
    MongoCollection<org.bson.Document> table = getMongoCollection();
    BasicDBObject searchQuery = new BasicDBObject("ecm:id", id);
    new ArrayList<>();
    FindIterable<org.bson.Document> iterable = table.find(searchQuery);
    iterable.forEach(new Block<org.bson.Document>() {
        @Override//  www . j a va2 s  . c  o m
        public void apply(final org.bson.Document document) {
            ArrayList<String> racl = document.get("ecm:racl", ArrayList.class);
            String[] acl = racl.toArray(new String[racl.size()]);
            Document doc = new Document(document.getString("ecm:id"), document.getString("ecm:primaryType"),
                    acl);
            ret[0] = doc;
        }
    });
    return ret[0];
}

From source file:org.nuxeo.tools.esync.db.DbMongo.java

License:Open Source License

@Override
public Set<String> getDocumentIdsForType(String type) {
    final Set<String> ret = new HashSet<>();
    MongoCollection<org.bson.Document> table = getMongoCollection();
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("ecm:primaryType", type);
    FindIterable<org.bson.Document> iterable = table.find(searchQuery);
    iterable.forEach(new Block<org.bson.Document>() {
        @Override//w  ww  .  ja  v a  2  s. c  o m
        public void apply(final org.bson.Document document) {
            ret.add(document.getString("ecm:id"));
        }
    });
    return ret;
}

From source file:org.pac4j.mongo.credentials.authenticator.MongoAuthenticator.java

License:Apache License

public void validate(UsernamePasswordCredentials credentials) {
    CommonHelper.assertNotNull("mongoClient", this.mongoClient);
    CommonHelper.assertNotNull("usernameAttribute", this.usernameAttribute);
    CommonHelper.assertNotNull("passwordAttribute", this.passwordAttribute);
    CommonHelper.assertNotNull("usersDatabase", this.usersDatabase);
    CommonHelper.assertNotNull("usersCollection", this.usersCollection);
    CommonHelper.assertNotNull("attributes", this.attributes);
    CommonHelper.assertNotNull("passwordEncoder", this.passwordEncoder);

    final String username = credentials.getUsername();

    final MongoDatabase db = mongoClient.getDatabase(usersDatabase);
    final MongoCollection<Document> collection = db.getCollection(usersCollection);
    final List<Document> users = new ArrayList<>();
    try (final MongoCursor<Document> cursor = collection.find(eq(usernameAttribute, username)).iterator()) {
        int i = 0;
        while (cursor.hasNext() && i <= 2) {
            users.add(cursor.next());// w  ww  .  j  a va2 s .c  om
            i++;
        }
    }

    if (users.size() == 0) {
        throw new AccountNotFoundException("No account found for: " + username);
    } else if (users.size() > 1) {
        throw new MultipleAccountsFoundException("Too many accounts found for: " + username);
    } else {
        final Map<String, Object> user = users.get(0);
        final String expectedPassword = passwordEncoder.encode(credentials.getPassword());
        final String returnedPassword = (String) user.get(passwordAttribute);
        if (CommonHelper.areNotEquals(returnedPassword, expectedPassword)) {
            throw new BadCredentialsException("Bad credentials for: " + username);
        } else {
            final MongoProfile profile = createProfile(username, attributes.split(","), user);
            credentials.setUserProfile(profile);
        }
    }
}

From source file:org.piotr.apollo.service.AnswerService.java

public List<Answer> getAnswers(ObjectId questionId) {
    MongoCollection collection = db.getCollection(answerCollection);

    List<Answer> answersList = new ArrayList<Answer>();

    Document findAnswers = new Document();

    findAnswers.append("question_id", questionId);

    FindIterable iterable = collection.find(findAnswers);

    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document document = cursor.next();

        Answer answer = new Answer();

        answer.setAnswer(document.getString("answer"));
        answer.setCorrect(document.getBoolean("correct"));
        answer.setQuestion_id((ObjectId) (document.get("question_id")));
        answer.setId(document.get("_id").toString());

        answersList.add(answer);/*  w w w.j a va  2  s  . com*/
    }

    return answersList;
}

From source file:org.piotr.apollo.service.FinishedService.java

public List<Finished> getAllFinishedTest(String lesson) {
    List<Finished> finishedList = new ArrayList<>();
    MongoCollection collection = mongoDb.getCollection(finishedCollection);

    Document doc = new Document();
    doc.append("lesson_id", new ObjectId(lesson));

    FindIterable iterable = collection.find(doc);
    MongoCursor<Document> cursor = iterable.iterator();
    while (cursor.hasNext()) {
        Document temp = cursor.next();

        Finished finished = new Finished();

        ObjectId finishedId = (ObjectId) temp.get("_id");
        ObjectId lessonId = (ObjectId) temp.get("lesson_id");

        finished.set_Id(finishedId);/*from ww w .jav a2  s  .  com*/
        finished.setLesson_id(lessonId);
        finished.setLessonId(lessonId.toString());
        finished.setId(finishedId.toString());
        finished.setCorrect(temp.getInteger("correct"));
        finished.setWrong(temp.getInteger("wrong"));
        finished.setPercentage(temp.getDouble("percentage"));

        finishedList.add(finished);
    }
    return finishedList;
}