Skip to content

Commit

Permalink
Adding group() method to Query object.
Browse files Browse the repository at this point in the history
  • Loading branch information
jwage committed May 20, 2010
1 parent 795dc99 commit e0116b9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Query
const TYPE_FIND = 1;
const TYPE_UPDATE = 2;
const TYPE_REMOVE = 3;
const TYPE_GROUP = 4;

/** The DocumentManager instance for this query */
private $_dm;
Expand Down Expand Up @@ -64,6 +65,9 @@ class Query
/** Skip a specified number of records (offset) */
private $_skip = null;

/** Group information. */
private $_group = array();

/** Pass hints to the MongoCursor */
private $_hints = array();

Expand Down Expand Up @@ -114,6 +118,16 @@ public function getDocumentManager()
return $this->_dm;
}

/**
* Get the type of this query.
*
* @return string $type
*/
public function getType()
{
return $this->_type;
}

/**
* Whether or not to hydrate the data into objects or to return the raw results
* from mongo.
Expand Down Expand Up @@ -235,6 +249,25 @@ public function remove($className = null)
return $this;
}

/**
* Perform an operation similar to SQL's GROUP BY command
*
* @param array $keys
* @param array $initial
* @param string $reduce
* @param array $condition
* @return Query
*/
public function group($keys, array $initial)
{
$this->_group = array(
'keys' => $keys,
'initial' => $initial
);
$this->_type = self::TYPE_GROUP;
return $this;
}

/**
* The fields to select.
*
Expand Down Expand Up @@ -730,6 +763,13 @@ public function execute(array $options = array())
return $this->_dm->getDocumentCollection($this->_className)
->update($this->_where, $this->_newObj, $options);
break;
case self::TYPE_GROUP;
return $this->_dm->getDocumentCollection($this->_className)
->group(
$this->_group['keys'], $this->_group['initial'],
$this->_mapReduce['reduce'], $this->_where
);
break;
}
}

Expand Down
9 changes: 9 additions & 0 deletions tests/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,13 @@ public function testUnsetFieldUpdateQuery()
->getSingleResult();
$this->assertFalse(isset($user['hits']));
}

public function testGroup()
{
$query = $this->dm->createQuery('Documents\User')
->group(array(), array('count' => 0))
->reduce('function (obj, prev) { prev.count++; }');
$result = $query->execute();
$this->assertEquals(1, $result['retval'][0]['count']);
}
}

0 comments on commit e0116b9

Please sign in to comment.