Retrieving Interactions Data from MongoDB using Sitecore Analytics API

Being a Sitecore Developer sometimes means that you have implemented or gonna implement Sitecore Analytics in your project soon. While implementing the same, we would end up in creating Reports with Charts/Tables using Analytics Data. For that, the first option that we would choose is to query the Reporting Database to get the interaction details from tables like Fact_PageViews or Fact_Visits.

If we need some customization in that, we would directly query the MongoDB using FindAll() or Find() methods and would get the entire collection, filter it. And this needs to be converted into a List/DataTable etc. and we would make it ready for binding,

//Accessing the Server & Database using MongoClient
string connectionString = ConfigurationManager.ConnectionStrings["analytics"].ConnectionString;
MongoUrl mongoUrl = new MongoUrl(connectionString);
MongoServer server = (new MongoClient(connectionString)).GetServer();
MongoDatabase database = server.GetDatabase(mongoUrl.DatabaseName);
 
//Get the Interactions Collection
var collection = database.GetCollection<BsonDocument>("Interactions").FindAll().ToList();

I was just thinking, Sitecore as a tool, why is it not providing some APIs to fetch the Analytics Data. And after a lot of research I was surprised to see that Sitecore has already got some APIs in it, which made my job much simpler than it should be,

Sitecore.Analytics.Reporting.MongoDbReportDataSource mongoDBSource = new Sitecore.Analytics.Reporting.MongoDbReportDataSource("analytics");
string query = "{collection: \"Interactions\",query: {_t: \"VisitData\"},fields: [\"_id\",\"ContactId\",\"StartDateTime\",\"EndDateTime\",\"Value\",\"VisitPageCount\"]}";
ReportDataQuery reportQuery = new ReportDataQuery(query);
DataTable interactions = mongoDBSource.GetData(reportQuery);

The query would have the following details,
• MongoDB Collection Name
• Query for filtering the Collection
• Fields that needs to be retrieved from MongoDB

And finally got the Reports ready using Telerik Charting controls that comes along with Sitecore,

I have got this done using Sitecore 7.5 and it should work in versions above 7.5. This will have major performance improvement in your Mongo DB Querying and you will not find a major impact when you upgrade your sitecore version, because Sitecore will take care of the API changes that might happen in the new MongoDB dlls.

Originally Posted at:  http://www.nttdatasitecore.com/Blog/2016/July/Retrieving-Interactions-Data-from-MongoDB-using-Sitecore-Analytics-API

One Reply to “Retrieving Interactions Data from MongoDB using Sitecore Analytics API”

Leave a Reply

Your email address will not be published. Required fields are marked *