Reputation: 171
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?
Upvotes: 0
Views: 723
Reputation: 2036
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
Upvotes: 2
Reputation: 11
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
:)
Upvotes: 0