paolo@bimodesign.com | +34 608 61 64 10

Framework

        

Zend 2 - Doctrine 2 and MongoDb (Select)

This is the third posts about Zend 2, Doctrine 2 and MongoDB installation and CRUD examples. In this article I'll show how find a document, using several methods. I'll show the find method, the queryBuilder, the eagerCursor etc...
These examples based on these my previous posts:

Installation and Configuration
CRUD - Insert/create document

Of course you can find all the methods and all the documentation at the Doctrine Oficial link
I created a show action into the user controller to make my tests.

    ...
    ... The header code of controller
    ...
	
    public function showAction()
    {
        $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
       
	// Find by Id
        $userFind = $dm->find('User\Document\User', '55b9f676e0cf20c9138b4567');

        // You can configure queries to return an eager cursor instead of a normal mongodb cursor using the 
        // Builder#eagerCursor() method:
        // From http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html
        
        $queryBuilder = $dm->createQueryBuilder('User\Document\User');

        //Cursor all data - EagerCursor
        $qb = $queryBuilder->eagerCursor(true);
        $query = $qb->getQuery();
        $cursor = $query->execute();
        
        foreach ($cursor as $user) { 
            // queries for all users and data is held internally
            // each User object is hydrated from the data one at a time.
            
            print_r($user);
        }
        
        //Cursor using where condition - EagerCursor
        $qb = $queryBuilder->eagerCursor(true)
                 ->field('name')->equals('Paolo');

        $query = $qb->getQuery();
        $cursorAll = $query->execute();
        
        foreach ($cursorAll as $user) { 
            // queries for all users and data is held internally
            // each User object is hydrated from the data one at a time.
            
            print_r($user);
        }
        
        //Single Result with query condition
        $userLimitOne = $queryBuilder->field('name')->equals('Paolo')
                 ->getQuery()
                 ->getSingleResult();

        print_r($userLimitOne);

        //Distinct example
        $qbDistinct = $queryBuilder->eagerCursor(true)
                                    ->distinct('name');
        $queryDistinct = $qbDistinct->getQuery();
        $usersArray = $queryDistinct->execute();
        
        foreach ($usersArray as $user) { 
            // queries for all users and data is held internally
            // each User object is hydrated from the data one at a time.
            
            print_r($user);
        }

        return new ViewModel();
    }

Note: You can download the entire proyect from my github account.