Installing MongoDB to work with Java (MongoDB Java Tutorial)
Java and MongoDB
Pssst! Here is a dirtly little secret. Don't tell your Node.js friends or Ruby friends this. More Java developers use MongoDB than Ruby and Node.js. They just are not as loud about it. Using MongoDB with Java is very easy.
The language driver for Java seems to be a straight port of something written with JavaScript in mind, and the usuability suffers a bit because Java does not have literals for maps/objects like JavaScript does. Thus an API written for a dynamic langauge does not quite fit Java. There can be a lot of useability improvement in the MongoDB Java langauge driver (hint, hint). There are alternatives to using just the straight MongoDB language driver, but I have not picked a clear winner (mjorm, morphia, and Spring data MongoDB support). I'd love just some usuability improvements in the core driver without the typical Java annotation fetish, perhaps a nice Java DAO DSL (see section on criteria DSL if you follow the link).
Setting up Java and MongoDB
Let's go ahead and get started then with Java and MongoDB.
Download latest mongo driver from github (https://github.com/mongodb/mongo-java-driver/downloads), then put it somewhere, and then add it to your classpath as follows:
$ mkdir tools/mongodb/lib $ cp mongo-2.7.3.jar tools/mongodb/lib
Assuming you are using Eclipse, but if not by now you know how to translate these instructions to your IDE anyway. The short story is put the mongo jar file on your classpath. You can put the jar file anywhere, but I like to keep mine in ~/tools/.
If you are using Eclipse it is best to create a classpath variable so other projects can use the same variable and not go through the trouble. Create new Eclipse Java project in a new Workspace. Now right click your new project, open the project properties, go to the Java Build Path->Libraries->Add Variable->Configure Variable shown in figure 7.
Figure 7: Adding Mongo jar file as a classpath variable in Eclipse
For Eclipse from the "Project Properties->Java Build Path->Libraries", click "Add Variable", select "MONGO", click "Extend…", select the jar file you just downloaded.
Figure 8: Adding Mongo jar file to your project
Once you have it all setup, working with Java and MongoDB is quite easy as shown in figure 9.
Figure 9 Using MongoDB from Eclipse
The above is roughly equivalent to the console/JavaScript code that we were doing earlier. TheBasicDBObject is a type of Map with some convenience methods added. The DBCursor is like a JDBC ResultSet. You execute queries with DBColleciton. There is no query syntax, just finder methods on the collection object. The output from the above is:
Out: { "_id" : { "$oid" : "4f964d3000b5874e7a163895"} , "name" : "Rick Hightower" , "gender" : "m" , "phone" : "520-555-1212" , "age" : 42.0} { "_id" : { "$oid" : "4f984cce72320612f8f432bb"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30}
Once you create some documents, querying for them is quite simple as show in figure 10.
Figure 10: Using Java to query MongoDB
The output from figure 10 is as follows:
Rick? { "_id" : { "$oid" : "4f964d3000b5874e7a163895"} , "name" : "Rick Hightower" , "gender" : "m" , "phone" : "520-555-1212" , "age" : 42.0} Diana? { "_id" : { "$oid" : "4f984cae72329d0ecd8716c8"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30} Diana by object id? { "_id" : { "$oid" : "4f984cce72320612f8f432bb"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30}
Just in case anybody wants to cut and paste any of the above, here it is again all in one go in the following listing.
Listing: Complete Java Listingpackage com.mammatustech.mongo.tutorial; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.DB; public class Mongo1Main { public static void main (String [] args) throws Exception { Mongo mongo = new Mongo(); DB db = mongo.getDB("tutorial"); DBCollection employees = db.getCollection("employees"); employees.insert(new BasicDBObject().append("name", "Diana Hightower") .append("gender", "f").append("phone", "520-555-1212").append("age", 30)); DBCursor cursor = employees.find(); while (cursor.hasNext()) { DBObject object = cursor.next(); System.out.println(object); } //> db.employees.find({name:"Rick Hightower"}) cursor=employees.find(new BasicDBObject().append("name", "Rick Hightower")); System.out.printf("Rick?\n%s\n", cursor.next()); //> db.employees.find({age:{$lt:35}}) BasicDBObject query = new BasicDBObject(); query.put("age", new BasicDBObject("$lt", 35)); cursor=employees.find(query); System.out.printf("Diana?\n%s\n", cursor.next()); //> db.employees.findOne({_id : ObjectId("4f984cce72320612f8f432bb")}) DBObject dbObject = employees.findOne(new BasicDBObject().append("_id", new ObjectId("4f984cce72320612f8f432bb"))); System.out.printf("Diana by object id?\n%s\n", dbObject); } }
Please note that the above is completely missing any error checking, or resource cleanup. You will need do some of course (try/catch/finally, close connection, you know that sort of thing).
If you would like to learn more about MongoDB consider the following resources:
Mongo DB is wrong, MongoDB always put the DB next to Mongo.
|
No comments:
Post a Comment