Example usage for com.mongodb.client MongoCursor next

List of usage examples for com.mongodb.client MongoCursor next

Introduction

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

Prototype

@Override
    TResult next();

Source Link

Usage

From source file:swm.project.loadDataToDb.GetDataFromDb.java

public List<String> getMovieDetails(List<Integer> movieID) {
    MongoCollection<Document> movieNamesCollection = db.getCollection(Consts.MOVIE_NAME_DATA);
    //FindIterable<Document> movieNamesAll = movieNamesCollection.find();
    //MongoCursor movieNamesCursorX = movieNamesAll.iterator();
    ArrayList<String> names = new ArrayList<>();
    BasicDBObject whereQuery = new BasicDBObject();
    for (int i = 0; i < movieID.size(); i++) {
        whereQuery.put("_id", movieID.get(i));
        FindIterable<Document> iterate = movieNamesCollection.find(whereQuery);
        MongoCursor cursor = iterate.iterator();
        while (cursor.hasNext()) {
            Document ratingFields = (Document) cursor.next();
            String movieName = (String) ratingFields.get(Consts.MOVIE_NAME_FIELD);
            //System.out.println(movieName);          
            names.add(movieName);/*from  w w  w  .  java2s . c o  m*/
        }
    }
    return names;
}

From source file:tour.NewQuickTour.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
 *//* ww w  .  jav  a 2s .co  m*/
public static void main(final String[] args) {
    MongoClient mongoClient;

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

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

    database.drop();

    // get a list of the collections in this database and print them out
    List<String> collectionNames = database.listCollectionNames().into(new ArrayList<String>());
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

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

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

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

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur);
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc);

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // max time
    collection.find().maxTime(1, TimeUnit.SECONDS).first();

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.dropDatabase("databaseToBeDropped");

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // create an ascending index on the "i" field
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index);
    }

    // create a text index on the "content" field
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    Document search = new Document("$search", "textual content -irrelevant");
    Document textSearch = new Document("$text", search);
    long matchCount = collection.count(textSearch);
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new Document("$text", search.append("$language", "english"));
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc);

    // release resources
    mongoClient.close();
}

From source file:twitterapp.TweetsSimilarity.java

/**
 * @param args the command line arguments
 *///from   ww w .j a v a2 s. c  om
public static void main(String[] args) throws JSONException, Exception {
    System.out.println(intersection("unpresidented", "unpresidented", "unpresidented"));
    System.out.println(union("unpresidented", "unpresidented", "unpresidented"));
    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("myTweetdb");

    Document temp;
    JSONObject b, c;
    Double sim[] = new Double[100];
    // String one = a.getString("hashtag");
    String two = "";
    int j = 0;
    int k = 0;
    int y = 0;
    String[] collections = { "hashtagAll", "mentionedAll", "urlAll", "retweetedAll" };
    String[] entities = { "hashtag", "mentioned_users", "url", "retweeted_tweet" };
    Double[][] hashtag = new Double[1000][1000];
    for (j = 0; j < hashtag.length; j++) {
        Arrays.fill(hashtag[j], 0.0);
    }
    j = 0;
    for (int p = 0; p < collections.length; p++) {

        String file = collections[p].concat(".csv");
        System.out.println(file);
        PrintWriter writer = new PrintWriter(file);
        writer.println("Source,Target,Weight,Type");
        MongoCursor<Document> manasou;
        MongoCollection collection2 = database.getCollection(collections[p]);
        manasou = collection2.find().iterator();
        HashMap<String, Integer> count = new HashMap<>();
        String common = "";

        while (manasou.hasNext() && y < 1000) {
            b = new JSONObject(manasou.next());
            String temp1 = b.getString(entities[p]);
            String tokens[] = temp1.split(" ");
            for (int i = 0; i < tokens.length; i++) {
                if (count.containsKey(tokens[i])) {
                    Integer temp2 = count.get(tokens[i]);
                    temp2++;
                    count.replace(tokens[i], temp2);
                } else {
                    count.put(tokens[i], 1);
                }
            }
            y++;
        }
        Iterator<Entry<String, Integer>> count_it = count.entrySet().iterator();
        while (count_it.hasNext()) {
            Entry entry = count_it.next();
            if ((Integer) entry.getValue() > 500) {
                common = common.concat(entry.getKey() + " ");
            }
        }
        System.out.println(common);
        manasou = collection2.find().iterator();
        j = 0;
        while (manasou.hasNext() && j < 1000) {
            b = new JSONObject(manasou.next());
            System.out.println(j);
            MongoCursor<Document> kati2 = collection2.find().iterator();
            k = 0;
            while (kati2.hasNext() && k < 1000) {
                c = new JSONObject(kati2.next());
                if (j < k) {
                    String temp1 = b.getString(entities[p]);
                    String temp2 = c.getString(entities[p]);
                    double temp3 = intersection(temp1, temp2, common) / union(temp1, temp2, common);
                    if (Double.isNaN(temp3)) {
                        temp3 = 1;
                    }
                    String lel = "tweet" + j + "," + "tweet" + k + "," + temp3 + ",Undirected";

                    hashtag[j][k] = hashtag[j][k] + temp3;

                    writer.flush();
                    if (temp3 > 0.2) {
                        writer.println(lel);
                    }

                } else {
                    k++;
                    continue;
                }
                k++;
            }

            j++;

        }

    }
    PrintWriter writer = new PrintWriter("all.csv");
    writer.println("Source,Target,Weight,Type");
    for (j = 0; j < hashtag.length; j++) {
        for (k = 0; k < hashtag.length; k++) {
            if (j < k) {
                double temp1 = hashtag[j][k] / 4.0;
                if (temp1 > 0.2) {
                    String lel = "tweet" + j + "," + "tweet" + k + "," + temp1 + ",Undirected";
                    writer.flush();
                    writer.println(lel);
                }
            }
        }
    }

}

From source file:uniandes.edu.twitterreader.TwitterApp.java

public void getMongoFunctionResults(String functionStringWithParameters) {
    Document doc2 = mongoDB.runCommand(new Document("$eval", functionStringWithParameters));
    String collectionResults = doc2.getString("retval");

    mongoResults.clear();// w w w.ja v  a 2s .c o m

    MongoCursor cursor = mongoDB.getCollection(collectionResults).find().iterator();

    while (cursor.hasNext()) {
        String resultString = cursor.next().toString();

        // obtener propiedades del resultado
        String hashtag = getValueFromMongoResult(resultString, "hashtag", false),
                user = getValueFromMongoResult(resultString, "user", false),
                date = getValueFromMongoResult(resultString, "date", false),
                sentiment = getValueFromMongoResult(resultString, "sentiment", false);

        float tweets = Float.parseFloat(getValueFromMongoResult(resultString, "totalTweets", true)),
                retweets = Float.parseFloat(getValueFromMongoResult(resultString, "totalReTweet", true)),
                followers = Float.parseFloat(getValueFromMongoResult(resultString, "totalFollowers", true));

        mongoResults.add(new MongoDataRecord(hashtag, user, date, sentiment, tweets, retweets, followers));

        System.out.println(hashtag + "|" + user + "|" + date + "|" + sentiment + "|" + tweets + "|" + retweets
                + "|" + followers);
    }
}

From source file:wetree.Wetree.java

private static void mongoTest(WebEntityPageTree wept) {

    // Creating a mongo cursor
    MongoConnector connector = new MongoConnector();
    MongoCursor<Document> cursor = connector.getPagesCursor();

    int i = 0;/*from  w ww .  j av a 2  s.c  o  m*/
    ArrayList<PLink> plinks = new ArrayList<>();
    while (cursor.hasNext()) {
        Document doc = cursor.next();
        String lru = doc.getString("lru");

        // First we need to add the page's lru
        wept.addPage(lru);

        // Second we need to add the page's lrulinks
        List<String> lrulinks = (List<String>) doc.get("lrulinks");
        System.out.println((i++) + " (" + lrulinks.size() + ") " + lru);

        lrulinks.forEach((String lrulink) -> {
            plinks.add(new PLink(lru, lrulink));
        });
    }

    wept.addPlinks(plinks);
}