In this recipe, we are going to create a BeanShell data source, just as we did in previous reporting recipes. This BeanShell data source, a lightweight scripting for Java (http://www.beanshell.org), will allow us to query data from MongoDB.
To get ready for this recipe, you first need to start the MongoDB server with the same database as that of the last chapter. You will also need to start the Pentaho BA Server using the server control scripts. Once it is started, you should be able to log in to the BI Server.
Proceed with the following steps:
import com.mongodb.*; import org.pentaho.reporting.engine.classic.core.util.TypedTableModel; Mongo mongo = new Mongo("localhost",27017); db = mongo.getDB("SteelWheels"); orders = db.getCollection("Orders"); String[] columnNames = {"Country", "City", "Line", "TotalPrice"}; Class[] columnTypes = {String.class, String.class, String.class, Double.class}; TypedTableModel model = new TypedTableModel(columnNames, columnTypes); BasicDBObject dbo = new BasicDBObject(); docs= orders.find(dbo); while (docs.hasNext()) { doc = docs.next(); model.addRow(new Object[] { doc.get("customer").get("address").get("country"), doc.get("customer").get("address").get("city"), doc.get("product").get("line"), doc.get("totalPrice") }); } docs.close(); return model;
The following screenshot displays all the parameters:
Beanshell Data Source
.To test whether this data source works, we are going to execute the data source directly from the accompanying CDA file:
The query will execute once you have selected it from the Data Access drop-down menu. You will see the contents of the beanshell query that is attached to the dashboard you defined earlier.
In this recipe, we saw how to develop another way of extracting data from MongoDB to the dashboard components, using the MongoDB Java driver and beanshell scripting. We started by creating a new CDE dashboard and adding a BeanShell source to the data sources section. Then, we defined our BeanShell script to return a selection of data directly from MongoDB, using the MongoDB Java driver. Once we had saved the CDE dashboard, it generated an accompanying CDA file that would store all our data sources for the same dashboard. To test that the data source was working correctly, we opted to execute it directly from the generated CDA file. Then, we should be able to see that the beanshell scripts are executed successfully in the CDA file and return a list of orders from the MongoDB database.