In the previous post, we discussed the CRUD operations in MongoDB. It’s time to get your hands dirty by writing some code. Let’s connect to MongoDB from Java, access our Quiz document and play with the Questions collection.
- You need to download the MongoDB driver for Java here and add it to the classpath.
- Start your mongodb server from command prompt.
-
You can connect to the MongoDB server, get a reference to the Quiz document and the Questions collection as shown here;
DBAddress dbAddress = new DBAddress("localhost"); Mongo mongo = new Mongo(dbAddress); DB quiz = mongo.getDB("Quiz"); DBCollection questions = quiz.getCollection("Questions");
-
Let’s insert a record in Questions collections as shown here. You don’t have to supply a JSON formatted data. You can create an instance of BasicDBObject and push it. The data will get serialized to JSON and be inserted into the document.
BasicDBObject record = new BasicDBObject(); record.append("question", "10*9=?"); record.append("choices",new String[]{"19","1","90","100"}); record.append("answer", "90"); questions.insert(record);
-
Let’s fetch the data from the Questions collection. You can supply the query as a BasicDBObject instance and execute the records. You’ll get a DBCursor object that’s pretty similar to the ResultSet instance in JDBC.
BasicDBObject query = new BasicDBObject(); query.append("question","10*9=?"); DBCursor dbCursor = questions.find(query); while(dbCursor.hasNext()){ BasicDBObject record = (BasicDBObject)dbCursor.next(); System.out.println(record); }
The Java class with the complete code is shown here.
import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBAddress; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; public class QuestionsClient { public static void main(String[] args) throws Exception{ DBAddress dbAddress = new DBAddress("localhost"); Mongo mongo = new Mongo(dbAddress); DB quiz = mongo.getDB("Quiz"); DBCollection questions = quiz.getCollection("Questions"); //INSERT A QUESTION BasicDBObject record = new BasicDBObject(); record.append("question", "10*9=?"); record.append("choices",new String[]{"19","1","90","100"}); record.append("answer", "90"); questions.insert(record); //LOAD BasicDBObject query = new BasicDBObject(); query.append("question","10*9=?"); DBCursor dbCursor = questions.find(query); while(dbCursor.hasNext()){ BasicDBObject obj = (BasicDBObject)dbCursor.next(); System.out.println(obj); } } }