Created
July 11, 2012 03:33
-
-
Save iandaniel/3087822 to your computer and use it in GitHub Desktop.
Sample Java code for putting some data in a MongoDB collection. Then querying the collection, iterating over the results and extracting fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.UnknownHostException; | |
import com.mongodb.*; | |
public class CursorIteration | |
{ | |
public static void main(String[] args) throws UnknownHostException, MongoException | |
{ | |
Mongo mongo = new Mongo(); | |
DB db = mongo.getDB("play"); | |
DBCollection students = db.getCollection("students"); | |
populateStudents(students); | |
queryAndDisplayStudents(students); | |
} | |
private static void populateStudents(DBCollection students) | |
{ | |
BasicDBObject student1 = new BasicDBObject(); | |
student1.put("Name", "Bob Smythe"); | |
student1.put("SID", 1234); | |
student1.put("University", "Harvard"); | |
students.insert(student1); | |
BasicDBObject student2 = new BasicDBObject(); | |
student2.put("Name", "Mary Brown"); | |
student2.put("SID", 5678); | |
student2.put("University", "Yale"); | |
students.insert(student2); | |
BasicDBObject student3 = new BasicDBObject(); | |
student3.put("Name", "Mike Black"); | |
student3.put("SID", 9876); | |
student3.put("University", "Princeton"); | |
students.insert(student3); | |
} | |
private static void queryAndDisplayStudents(DBCollection students) | |
{ | |
// Get all students (no query criteria). | |
DBCursor cursor = students.find(); | |
// Iterate over the students. | |
while (cursor.hasNext()) | |
{ | |
// Display each student. | |
DBObject student = cursor.next(); | |
// Get the individual fields of the student document. | |
// These individual fields could, for example, be put in text fields of a GUI. | |
String name = (String) student.get("Name"); | |
Number sid = (Number) student.get("SID"); | |
String university = (String) student.get("University"); | |
// Given that we are not actually building a GUI, just display the fields on the command line. | |
System.out.printf("Student name: %s, SID: %d, University: %s%n", name, sid, university); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment