In this post I will show how to add an effective hit counter to shiny applications using a remote database server (MongoHQ). Much of my code follows the MongoHQ package demo found at http://docs.mongohq.com/languages/r.html
Start and account with MongoHQ. A Sandbox free database account with 512 MB of memory should be more than sufficient.
Once you have started an account you need to log into app.mongohq.com and start a database as well as a collection. Within a database you will need to select the admin tab as well in order to create a user id which you can use to log into the collection.
The following code is what I use to create a hit counter.
# Load the CRAN library library(rmongodb) # You can find the host information for the collection under the admin tab. host <- "myarea.mongohq.com:myport" username <- "mycreateduser" password <- "mycreatedpassword" db <- "mydatabase" mongo <- mongo.create(host=host , db=db, username=username, password=password) # Load the collection. In this case the collection is. collection <- "OLS-app" namespace <- paste(db, collection, sep=".") # Insert a simple entry into the collection at the time of log in # listing the date that the collection was accessed. b <- mongo.bson.from.list(list(platform="MongoHQ", app="counter", date=toString(Sys.Date()))) ok <- mongo.insert(mongo, namespace, b) # Now we query the database for the number of hits buf <- mongo.bson.buffer.create() mongo.bson.buffer.append(buf, "app", "counter") query <- mongo.bson.from.buffer(buf) counter <- mongo.count(mongo, namespace, query) # I am not really sure if this is a good way of doing this # at all. # I send the number of hits to the shiny counter as a renderText # reactive function paste0("Hits: ", counter)
The now database run hit counter can be seen at:
You can find the updated code at github