Using Mongo indexes with Phalcon ODM (ensureIndex)

February 11th 2014

I've realised there's something missing from Phalcon's ODM. But that's not too bad, thankfully, it's easy to implement yourself.

Basically, in the \MongoCollection class you've got the method `ensureIndex()` which adds (or rather ensures) that your indexes exist.

Phalcon doesn't seem to have this (or if it does then I haven't found it).

I've just rolled my own way of doing this, and hopefully it helps someone out there.

To ensureIndex in the Phalcon ODM, I'm currently using:

PHP Code:
<?php
namespace My\ObjectNamespace;

class 
MyObject extends \Phalcon\Mvc\Collection
{
    public function 
ensureIndex()
    {
        
// Get the raw \MongoDB Connection
        
$connection $this->getConnection();

        
// Get the \MongoCollection connection (with added dynamic collection name (thanks Phalcon))
        
$collection $connection->selectCollection($this->getSource());

        
// One index.
        
$collection->ensureIndex(
            array(
'created' => -1)
        );

        
// A unique index
        
$collection->ensureIndex(
            array(
'name' => 1),
            array(
'unique' => true)
        );
    }
}

That's it. I've tied my Indexes into the Phalcon CLI http://docs.phalconphp.com/en/latest/reference/cli.html

But arguably you can call it however you want.

Ben commented on Mar 5th 2014

I've been looking for a "best practice" to ensure indexes using in Phalcon's Mvc Collection. So far it looks like this might be the most reasonable solution. Thanks!

Dinesh commented on Jul 29th 2015

Hi Thomas:I'm taking the same class as you! Thank you so, so much for bloniggg about it. I'm behind on the work because I chose to use Python 3.x instead of 2.x so I have to figure a way around some of the installations, like using Distribute instead of the Setup Tools, and I haven't gotten Bottle installed yet. I see on the boards that there's a fellow who posted some gists on Github about how to do this so I'm giving that a shot today. I am new to Python and Github and MongoDB, so I've got a lot of learning to do as quickly as I can. I don't care about the certificate of completion for the class, I just want to learn. Keep on bloggin'!Thanks,Vickie C.