views:

40

answers:

1

What are some good ways to store Analytics data using MongoDB for future analysis? I am thinking of doing something like:

> db.analytics.insert( { page: 'product', id: 123, date: new Date('Sept 8, 2010'),
                       pageviews: 222, timeOnPage: 5432 } )

> db.analytics.find()
{ "_id" : ObjectId("4c8e04b1f14d4366465197b8"), "page" : "product", "id" : 123, 
  "date" : "Wed Sep 08 2010 00:00:00 GMT-0700 (PDT)", "pageviews" : 222, 
  "timeOnPage" : 5432 }

which is quite relational. pageviews and timeOnPage can be lumped into

> db.analytics.insert({page: 'product', id: 123, date: new Date('Sept 8, 2010'),
                       data: { pageviews: 222, timeOnPage: 5432 } })

although if using Mongoid (a Rails Object Relation Mapper), then there is more complication for having an additional model.

A: 

You may want to look at using upserts and the $inc operator on counters. If pageviews increments you can use something like this (selector, operator, upsert set to true)

update( { page: 'product', id: 123, data: { pageviews: 222}) }, { $inc : { pageviews: 1} }, { upsert : true } )

If no document exists for this record it will create one, if one exists it will increment the pageviews.

It really all depends on how your data is shaped.

This blog explains more http://blog.mongodb.org/post/171353301/using-mongodb-for-real-time-analytics

CountCet