0

So, I read my MongoDB this way:

        mongo = new MongoClient("localhost", 27017);
        // Accessing the database
        MongoDatabase database = mongo.getDatabase("myDb");
        MongoCollection<Document> collection = database.getCollection("searchresults");

        // Getting the iterable object
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;

        // Getting the iterator
        Iterator it = iterDoc.iterator();

        while (it.hasNext()) {
            System.out.println(it.next());
            i++;
        }
    }

As you can see, each line has several columns: Title, etc. So, when I iterate over myDB, i want to parse each line by its value instead of get all in one line.

Any suggestions?

3
  • So the question is how to read a result rather than actually parsing a file? A hint: You're already looping over your results in your while loop. Put your it.next() call into a Document variable and see what kind of getters you can call on it. You can use that to investigate how to retrieve the data you need. Commented Sep 18, 2018 at 11:41
  • this it.next() get only Object Commented Sep 18, 2018 at 11:47
  • If you declare your iterator with generics by using Iterator<Document>, Java will see that a Document instance is expected when it.next() is called. Commented Sep 18, 2018 at 12:41

2 Answers 2

2

You can try reading into a Document structure, then run another loop across each of the entries. This will give each value on its own line.

FindIterable<Document> iterDoc = database.getCollection("").find();
for(Document doc : iterDoc) {
    for(Map.Entry<String, Object> entry : doc.entrySet()) {
        System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
    }
}

If you only want certain keys, use a projection in your find query

Sign up to request clarification or add additional context in comments.

Comments

0

This is not a fitting answer to your question, but i would look in to a concept thats called Object-Document-Mapping (ODM). It simplifies some boilerplate code that you have to care about. A common library for MongoDB-ODM is called Morphia :)

2 Comments

So i did not understand what i have to do
You can use it.next() to iterate to the document entrySet. But i would use morphia :) just an advice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.