Mongo Datatables
Mongo Datatables
June 2012 NY MongoDB User Group June 19, 2012 Jim OHara
http://datatables.net
<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>
$(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