views:

49

answers:

2

We use MongoDB to collect logs on pageviews.

$collection_name = "logs.".date('Y').".".date('m').".".date('d');
$collection = $this->Mongo->$collection_name;
$collection->insert($pageview);

The code above creates a new collection for every day.

I would like to be able to create an index on the above collection when it is created. Is there anyway to do this?

  1. In a traditional RDBMS, this is accomplished through the schema. Is there anything similar in MongoDB? Is it possible to configure the database to create indexes on new collections?
  2. If not, what is the best way to accomplish this in PHP? I don't want to call ensureIndex everytime I call insert
+1  A: 

To avoid calling ensureIndex on every insert I think your best bet (besides using only 1 collection which you have performance issues with) would be to run a cron-job every day at, say, 11pm which creates the collection/index for the collection corresponding to the upcoming day.

thenduks
+3  A: 

You can pre-create them, since it's not exactly a secret what collections you'll need :)

You could run something like:

for ($month = 0; $month < 12; $month++) {
    for ($day = 0; $day < 31, $day++) {
       $c = $db->getCollection("logs.2010.$month.$day");
       $c->ensureIndex(array("foo" => 1));
    }
}

ensureIndex will create the collection if it doesn't already exist.

kristina