Dynamic Data Display With jQuery, DataTables and MongoDB
June 2012 NY MongoDB User Group June 19, 2012 Jim OHara
http://datatables.net
Setting up the html
Add the html elements Add headers in a <thead> Include an id tag for the table
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th width="10">Last Name</th> <th width="10">First Name</th> <th width="10">Age</th> <th width="25">Location</th> <th width="10">Date</th> <th width="5">Fatal</th> </tr> </thead> <tbody> </tbody> </table>
Setting up the html
This script is added in a script tag following references to jQuery and Datables. These are the table cell elements Script will run on document load. Datatables will read each value with the mDataProp, and populate the JSON in a table cell. MongoServlet is the name of the Java class that will run. Servlet will reference a collection in MongDB and return a JSON object.
$(document).ready(function() { var oTable = $('#example').dataTable( { "bProcessing": true, "bPaginate": true, "bProcessing": true, "bDeferRender":true, "iDisplayLength":250, "sAjaxSource": "MongoServlet", "sScrollY": "400px", "aoColumns": [ { "mDataProp": "lname"}, { "mDataProp": "fname"}, { "mDataProp": "age", "sClass": "center"}, { "mDataProp": "location"}, { "mDataProp": "date"}, { "mDataProp": "fatal", "sClass": "center"} ] } );
db.miners.findOne()
{ "_id" : "ObjectID(4fde364a.."), "lname" : "ABAHAZY", "fname" : "JOHN", "location" : "WOODWARD", age" : "37", "fatal" : "Y", "date" : "1905/09/30" }
MongoServlet (snippets)
m = new Mongo("localhost"); protected void doPost(() PrintWriter out = response.getWriter(); DB db = m.getDB("test"); DBCollection coll = db.getCollection("miners"); DBCursor cursor = coll.find(); JSONObject miners = new JSONObject(); Map map = new LinkedHashMap(); List items = new ArrayList();
MongoServlet (snippets)
while(cursor.hasNext()) { Miner miner = new Miner(); // a simple POJO DBObject dbObject = cursor.next(); String lname = String.valueOf(dbObject.get("lname")); String fname = String.valueOf(dbObject.get("fname")); String age = String.valueOf(dbObject.get("age")); String date = String.valueOf(dbObject.get("date")); String fatal = String.valueOf(dbObject.get("fatal")); String location = String.valueOf(dbObject.get("location")).toUpperCase(); miner.setLname(lname); miner.setFname(fname); miner.setAge(age); miner.setFatal(fatal); miner.setLocation(location); miner.setDate(date); items.add(miner); }
MongoServlet (snippets)
map.put("sEcho", "1"); map.put("iTotalRecords", items.size()); map.put("iTotalDisplayRecords", items.size()); map.put("aaData", items); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(map); System.out.println(jsonString); out.print(jsonString); // JSON will be returned to the calling page
http://localhost:8080/tables/datatables.jsp