Tweetegy On the edge of chaos with Ruby, Rails, JavaScript and AngularJS.

| About | Search | Archive | Github | RSS |

Install MongoDB and load dummy logging data using MongoMapper

It turns out to be very easy to install Mongo DB on Ubuntu, so I will not go into detail too much here. If you follow these instructions then MongoDB will start after the installation completes and you can try it out at the console as follows (Note: The first command will fire up the Mongo DB shell and the second will list all the databases):

mongo
show dbs

The shell is probably the best way to get started with MongoDB. Here are some more details on using the MongoDB shell. Or just type help in the console!

Another useful trick to note is that it’s possible to get some administrative details about the server by pointing your browser to the following location: http://localhost:28017/. This displays details like version number, database stats, namespace information etc.

Loading MongoDB with test data.

There are three ways to insert data directly into MongoDB. There is the standard insert command which inserts one document at a time, there is the batch insert which can be used to insert multiple documents at a time (this is more efficient than inserting one at a time), or there is the mongoimport command line utility for running a raw data import from a relational database like MySQL. Many of these I will cover in future posts.

There also are indirect ways to load data namely via database language adapters like MongoMapper for Ruby. Here is an example of generating random data and loading it into MongoDB:

 1 require 'rubygems'
 2 require 'mongo'
 3 require 'mongo_mapper'
 4 require 'faker'
 5 require 'WebAppVisitorLog'
 6 
 7 #Create a couple of types of documents (see the classes)
 8 MongoMapper.database = "mongodb-logging"
 9 
10 WebAppVisitorLog.destroy_all
11 
12 10000.times {|n|
13   user_id = (1..1000).to_a.rand
14   session_id = (1..10000).to_a.rand
15   updated_at = (1..35).to_a.rand.days.ago
16 
17   @log = WebAppVisitorLog.create(
18             {
19               :session_id => session_id,
20               :user_id => user_id,
21               :updated_at => updated_at
22             })
23   @log.save()
24 }

Here is the code for the WebAppVisitorLog class:

1 class WebAppVisitorLog
2   include MongoMapper::Document
3 
4   key :session_id, Integer
5   key :user_id, Integer
6 end