Views and Map-Reduce Queries ============================ CouchDB uses views filtered through map-reduce to query all the documents of your database. Each view has a map- and optionally a reduce-function. Doctrine CouchDB ODM allows you to create and query views in your application. Creating and Managing Views --------------------------- Views are best managed as a folder structure in the filesystem. Create a Directory "couchdb/views" and instantiate a ``FolderDesignDocument`` in the following way and create the design document in the database: .. code-block:: php getData(); $couchClient->createDesignDocument("myapp", $view); If the directory structure now looked like the following: :: couchdb/ views/ username/ map.js article-dates/ map.js reduce.js It will create two views "username" and "article-dates" with corresponding map and reduce functions. For example the username map.js might look like: .. code-block:: javascript function(doc) { if (doc.type == 'Doctrine.Tests.Models.CMS.CmsUser') { emit(doc.username, doc._id); } } Querying Views -------------- To query a view from Doctrine CouchDB ODM you have to register it with its design document name in the CouchDB ODM Configuration: .. code-block:: php getConfiguration(); $config->addDesignDocument( "myapp", "Doctrine\CouchDB\View\FolderDesignDocument", "path/to/app/couchdb" ); You can then create either a native or a odm-query by calling either ``DocumentManager#createNativeQuery($designDocName, $viewName)`` or ``DocumentManager#createQuery($designDocName, $viewName)``. The difference between both queries is their result and some parameters. The ODM query will return instances of php objects that map to the CouchDB documents and the native query will return only convert the json to arrays that have been fetched from the CouchDB. Both queries have a common base class with a simple API: .. code-block:: php createQuery("myapp", "username"); $result = $query->setStartKey("b") ->setEndKey("c") ->setLimit(100) ->setSkip(20) ->onlyDocs(true) ->execute(); This will return all usernames starting with "b" and ending with "c", skipping the first 20 results and limiting the result to 100 documents. View Results ------------ The result of a view is an instance of ``Doctrine\CouchDB\View\Result``. It implements ``Countable``, ``IteratorAggregate`` and ``ArrayAccess``. If you specify ``onlyDocs(true)`` each result-row will contain only the associated document, otherwise the document is on the row index "doc" of the query. The following snippet shows the difference: .. code-block:: php createQuery("myapp", "username"); $result = $query->setStartKey("b") ->setEndKey("c") ->setLimit(100) ->setSkip(20) ->onlyDocs(true) ->execute(); foreach ($result AS $user) { echo $user->getUsername() . "\n"; } $query->onlyDocs(false); $result = $query->execute(); foreach ($result AS $userRow) { echo $userRow['doc']->getUsername() . "\n"; }