Skip to content
This repository has been archived by the owner on Nov 11, 2020. It is now read-only.

Commit

Permalink
Support $elemMatch in query projections (closes #101)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmikola committed Apr 23, 2013
1 parent 68a820f commit d51a44d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/Doctrine/MongoDB/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,22 @@ public function selectSlice($fieldName, $skip, $limit = null)
return $this;
}

/**
* Select a matching embedded document from an array field.
*
* @param string $fieldName
* @param array|Expr $expression
* @return Builder
*/
public function selectElemMatch($fieldName, $expression)
{
if ($expression instanceof Expr) {
$expression = $expression->getQuery();
}
$this->query['select'][$fieldName] = array($this->cmd . 'elemMatch' => $expression);
return $this;
}

/**
* Set the current field to operate on.
*
Expand Down
20 changes: 20 additions & 0 deletions tests/Doctrine/MongoDB/Tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,26 @@ private function provideProjections($include)
);
}

public function testSelectElemMatchWithArray()
{
$qb = $this->getTestQueryBuilder()
->selectElemMatch('addresses', array('state' => 'ny'));

$expected = array('addresses' => array('$elemMatch' => array('state' => 'ny')));

$this->assertEquals($expected, $qb->debug('select'));
}

public function testSelectElemMatchWithExpr()
{
$qb = $this->getTestQueryBuilder();
$qb->selectElemMatch('addresses', $qb->expr()->field('state')->equals('ny'));

$expected = array('addresses' => array('$elemMatch' => array('state' => 'ny')));

$this->assertEquals($expected, $qb->debug('select'));
}

private function getTestQueryBuilder()
{
return $this->conn->selectCollection('db', 'users')->createQueryBuilder();
Expand Down

0 comments on commit d51a44d

Please sign in to comment.