You are browsing a version that is no longer maintained.

Query Builder API

Querying for documents with Doctrine is just as simple as if you weren't using Doctrine at all. Of course you always have your traditional find() and findOne() methods but you also have a Query object with a fluent API for defining the query that should be executed.

The Query object supports several types of queries

  • FIND
  • FIND_AND_UPDATE
  • FIND_AND_REMOVE
  • INSERT
  • UPDATE
  • REMOVE
  • DISTINCT_FIELD
  • GEO_LOCATION

This section will show examples for the different types of queries.

Finding Documents

You have a few different ways to find documents. You can use the find() method to find a document by its identifier:

1<?php $users = $dm->find(User::class, $id);
2
3

The find() method is just a convenience shortcut method to:

1<?php $user = $dm->getRepository(User::class)->find($id);
2
3

The find() method checks the local in memory identity map for the document before querying the database for the document.

On the DocumentRepository you have a few other methods for finding documents:

  • findBy - find documents by an array of criteria
  • findOneBy - find one document by an array of criteria
1<?php $users = $dm->getRepository(User::class)->findBy(['type' => 'employee']); $user = $dm->getRepository(User::class)->findOneBy(['username' => 'jwage']);
2
3
4

Creating a Query Builder

You can easily create a new Query\Builder object with the DocumentManager::createQueryBuilder() method:

1<?php $qb = $dm->createQueryBuilder(User::class);
2
3

The first and only argument is optional, you can specify it later with the find(), update() (deprecated), updateOne(), updateMany() or remove() method:

1<?php $qb = $dm->createQueryBuilder(); // ... $qb->find(User::class);
2
3
4
5
6
7

Executing Queries

You can execute a query by getting a Query through the getQuery() method:

1<?php $qb = $dm->createQueryBuilder(User::class); $query = $qb->getQuery();
2
3
4

Now you can execute() that query and it will return an Iterator for you to iterate over the results:

1<?php $users = $query->execute();
2
3

Debugging Queries

While building not complicated queries is really simple sometimes it might be hard to wrap your head around more sophisticated queries that involves building separate expressions to work properly. If you are not sure if your the query constructed with Builder is in fact correct you may want to debug() it

1<?php $qb = $dm->createQueryBuilder(User::class); $query = $qb->getQuery(); $debug = $query->debug();
2
3
4
5

At this point your query is prepared - that means ODM done all its job in renaming fields to match their database name, added discriminator fields, applied filters, created correct references and all other things you employ ODM to. The array returned by ->debug() is what is passed to the underlying driver for the query to be performed.

Getting Single Result

If you want to just get a single result you can use the Query#getSingleResult() method:

1<?php $user = $dm->createQueryBuilder(User::class) ->field('username')->equals('jwage') ->getQuery() ->getSingleResult();
2
3
4
5
6

Selecting Fields

You can limit the fields that are returned in the results by using the select() method:

1<?php $qb = $dm->createQueryBuilder(User::class) ->select('username', 'password'); $query = $qb->getQuery(); $users = $query->execute();
2
3
4
5
6

In the results only the data from the username and password will be returned.

Index hints

You can force MongoDB to use a specific index for a query with the hint() method (see hint)

1<?php $qb = $dm->createQueryBuilder(User::class) ->hint('user_pass_idx'); $query = $qb->getQuery(); $users = $query->execute();
2
3
4
5
6

Combining select() and hint() on appropriate indexes can result in very fast covered queries

Selecting Distinct Values

Sometimes you may want to get an array of distinct values in a collection. You can accomplish this using the distinct() method:

1<?php $ages = $dm->createQueryBuilder(User::class) ->distinct('age') ->getQuery() ->execute();
2
3
4
5
6

The above would give you an array of all the distinct user ages!

MongoDB's distinct command does not support sorting, so you cannot combine distinct() with sort(). If you would like to sort the results of a distinct query, you will need to do so in PHP after executing the query.

Refreshing Documents

When a query (e.g. find) returns one or more hydrated documents whose identifiers are already in the identity map, ODM returns the managed document instances for those results. In this case, a managed document's data may differ from whatever was just returned by the database query.

The query builder's refresh() method may be used to instruct ODM to override the managed document with data from the query result. This is comparable to calling DocumentManager::refresh() for a managed document. The document's changeset will be reset in the process.

1<?php $user = $dm->createQueryBuilder(User::class) ->field('username')->equals('jwage') ->refresh() ->getQuery() ->getSingleResult(); // Jon's user will have the latest data, even if it was already managed
2
3
4
5
6
7
8
9

Refreshing is not applicable if hydration is disabled.

Fetching Documents as Read-Only

Similar to refresh(), readOnly() instructs ODM to not only hydrate the latest data but also to create new document's instance (i.e. if found document would be already managed by Doctrine, new instance will be returned) and not register it in UnitOfWork.

This technique can prove especially useful when using select() with no intent to update fetched documents.

1<?php $user = $dm->createQueryBuilder(User::class) ->field('username')->equals('malarzm') ->readOnly() ->getQuery() ->getSingleResult(); // Maciej's user will have the latest data, and will not be the same object // as the one that was already managed (if it was)
2
3
4
5
6
7
8
9
10

Read-Only is not applicable if hydration is disabled.

Read-only mode is not deep, i.e. any references (be it owning or inverse) of fetched WILL be managed by Doctrine. This is a shortcoming of current implementation, may change in future and will not be considered a BC break (will be treated as a feature instead).

To manage a document previously fetched in read-only mode, always use the merge method of the DocumentManager. Using persist in these cases can have unwanted side effects.

Disabling Hydration

For find queries the results by default are hydrated and you get document objects back instead of arrays. You can disable this and get the raw results directly back from mongo by using the hydrate(false) method:

1<?php $users = $dm->createQueryBuilder(User::class) ->hydrate(false) ->getQuery() ->execute(); print_r($users);
2
3
4
5
6
7
8

Limiting Results

You can limit results similar to how you would in a relational database with a limit and offset by using the limit() and skip() method.

Here is an example where we get the third page of blog posts when we show twenty at a time:

1<?php $blogPosts = $dm->createQueryBuilder(BlogPost::class) ->limit(20) ->skip(40) ->getQuery() ->execute();
2
3
4
5
6
7

Sorting Results

You can sort the results by using the sort() method:

1<?php $qb = $dm->createQueryBuilder(Article::class) ->sort('createdAt', 'desc');
2
3
4

If you want to an additional sort you can call sort() again. The calls are stacked and ordered in the order you call the method:

1<?php $query->sort('featured', 'desc');
2
3

Conditional Operators

The conditional operators in Mongo are available to limit the returned results through a easy to use API. Doctrine abstracts this to a fluent object oriented interface with a fluent API. Here is a list of all the conditional operation methods you can use on the Query\Builder object.

  • where($javascript)
  • in($values)
  • notIn($values)
  • equals($value)
  • notEqual($value)
  • gt($value)
  • gte($value)
  • lt($value)
  • lte($value)
  • range($start, $end)
  • size($size)
  • exists($bool)
  • type($type)
  • all($values)
  • mod($mod)
  • addOr($expr)
  • references($document)
  • includesReferenceTo($document)

Query for active administrator users:

1<?php $qb = $dm->createQueryBuilder(User::class) ->field('type')->equals('admin') ->field('active')->equals(true);
2
3
4
5

Query for articles that have some tags:

1<?php $qb = $dm->createQueryBuilder(Article::class) ->field('tags.name')->in(['tag1', 'tag2']);
2
3
4

Read more about the $in operator in the Mongo docs

Query for articles that do not have some tags:

1<?php $qb = $dm->createQueryBuilder(Article::class) ->field('tags.name')->notIn(['tag3']);
2
3
4

Read more about the $nin operator in the Mongo docs.

1<?php $qb = $dm->createQueryBuilder(User::class) ->field('type')->notEqual('admin');
2
3
4

Read more about the $ne operator in the Mongo docs.

Query for accounts with an amount due greater than 30:

1<?php $qb = $dm->createQueryBuilder(Account::class) ->field('amount_due')->gt(30);
2
3
4

Query for accounts with an amount due greater than or equal to 30:

1<?php $qb = $dm->createQueryBuilder(Account::class) ->field('amount_due')->gte(30);
2
3
4

Query for accounts with an amount due less than 30:

1<?php $qb = $dm->createQueryBuilder(Account::class) ->field('amount_due')->lt(30);
2
3
4

Query for accounts with an amount due less than or equal to 30:

1<?php $qb = $dm->createQueryBuilder(Account::class) ->field('amount_due')->lte(30);
2
3
4

Query for accounts with an amount due between 10 and 20:

1<?php $qb = $dm->createQueryBuilder(Account::class) ->field('amount_due')->range(10, 20);
2
3
4

Read more about conditional operators in the Mongo docs.

Query for articles with no comments:

1<?php $qb = $dm->createQueryBuilder(Article::class) ->field('comments')->size(0);
2
3
4

Read more about the $size operator in the Mongo docs.

Query for users that have a login field before it was renamed to username:

1<?php $qb = $dm->createQueryBuilder(User::class) ->field('login')->exists(true);
2
3
4

Read more about the $exists operator in the Mongo docs.

Query for users that have a type field that is of integer bson type:

1<?php $qb = $dm->createQueryBuilder(User::class) ->field('type')->type('integer');
2
3
4

Read more about the $type operator in the Mongo docs.

Query for users that are in all the specified Groups:

1<?php $qb = $dm->createQueryBuilder(User::class) ->field('groups')->all(['Group 1', 'Group 2']);
2
3
4

Read more about the $all operator in the Mongo docs.

1<?php $qb = $dm->createQueryBuilder(Transaction::class) ->field('field')->mod('field', [10, 1]);
2
3
4

Read more about the $mod operator in the Mongo docs.

Query for users who have subscribed or are in a trial.

1<?php $qb = $dm->createQueryBuilder(User::class); $qb->addOr($qb->expr()->field('subscriber')->equals(true)); $qb->addOr($qb->expr()->field('inTrial')->equals(true));
2
3
4
5

Read more about the $or operator in the Mongo docs.

The references() method may be used to query the owning side of a @ReferenceOne relationship. In the following example, we query for all articles written by a particular user.

1<?php // Suppose $user has already been fetched from the database $qb = $dm->createQueryBuilder(Article::class) ->field('user')->references($user);
2
3
4
5

The includesReferenceTo() method may be used to query the owning side of a @ReferenceMany relationship. In the following example, we query for the user(s) that have access to a particular account.

1<?php // Suppose $account has already been fetched from the database $qb = $dm->createQueryBuilder(User::class) ->field('accounts')->includesReferenceTo($account);
2
3
4
5

Update Queries

Doctrine also supports executing atomic update queries using the Query\Builder object. You can use the conditional operations in combination with the ability to change document field values atomically. Additionally if you are modifying a field that is a reference you can pass managed document to the Builder and let ODM build DBRef object for you.

You have several modifier operations available to you that make it easy to update documents in Mongo:

  • set($name, $value, $atomic = true)
  • setNewObj($newObj)
  • inc($name, $value)
  • unsetField($field)
  • push($field, $value)
  • addToSet($field, $value)
  • popFirst($field)
  • popLast($field)
  • pull($field, $value)
  • pullAll($field, array $valueArray)

Updating multiple documents

By default Mongo updates only one document unless multi option is provided and true. In ODM the distinction is done by explicitly calling updateMany() method of the builder:

1<?php $dm->createQueryBuilder(User::class) ->updateMany() ->field('someField')->set('newValue') ->field('username')->equals('sgoettschkes') ->getQuery() ->execute();
2
3
4
5
6
7
8

Modifier Operations

Change a users password:

1<?php $dm->createQueryBuilder(User::class) ->updateOne() ->field('password')->set('newpassword') ->field('username')->equals('jwage') ->getQuery() ->execute();
2
3
4
5
6
7
8

If you want to just set the values of an entirely new object you can do so by passing false as the third argument of set() to tell it the update is not an atomic one:

1<?php $dm->createQueryBuilder(User::class) ->updateOne() ->field('username')->set('jwage', false) ->field('password')->set('password', false) // ... set other remaining fields ->field('username')->equals('jwage') ->getQuery() ->execute();
2
3
4
5
6
7
8
9
10

Read more about the $set modifier in the Mongo docs.

You can set an entirely new object to update as well:

1<?php $dm->createQueryBuilder(User::class) ->setNewObj( [ 'username' => 'jwage', 'password' => 'password', // ... other fields ] ) ->field('username')->equals('jwage') ->getQuery() ->execute();
2
3
4
5
6
7
8
9
10
11
12
13

Increment the value of a document:

1<?php $dm->createQueryBuilder(Package::class) ->field('id')->equals('theid') ->field('downloads')->inc(1) ->getQuery() ->execute();
2
3
4
5
6
7

Read more about the $inc modifier in the Mongo docs.

Unset the login field from users where the login field still exists:

1<?php $dm->createQueryBuilder(User::class) ->updateMany() ->field('login')->unsetField()->exists(true) ->getQuery() ->execute();
2
3
4
5
6
7

Read more about the $unset modifier in the Mongo docs.

Append new tag to the tags array:

1<?php $dm->createQueryBuilder(Article::class) ->updateOne() ->field('tags')->push('tag5') ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Read more about the $push modifier in the Mongo docs.

Append new tags to the tags array:

1<?php $qb = $dm->createQueryBuilder(Article::class); $qb->updateOne() ->field('tags')->push($qb->expr()->each(['tag6', 'tag7'])) ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Add value to array only if its not in the array already:

1<?php $dm->createQueryBuilder(Article::class) ->updateOne() ->field('tags')->addToSet('tag1') ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Read more about the $addToSet modifier in the Mongo docs.

Add many values to the array only if they do not exist in the array already:

1<?php $qb = $dm->createQueryBuilder(Article::class); $qb->updateOne() ->field('tags')->addToSet($qb->expr()->each(['tag6', 'tag7'])) ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Remove first element in an array:

1<?php $dm->createQueryBuilder(Article::class) ->updateOne() ->field('tags')->popFirst() ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Remove last element in an array:

1<?php $dm->createQueryBuilder(Article::class) ->updateOne() ->field('tags')->popLast() ->field('id')->equals('theid') ->getQuery() ->execute();
2
3
4
5
6
7
8

Read more about the $pop modifier in the Mongo docs.

Remove all occurrences of value from array:

1<?php $dm->createQueryBuilder(Article::class) ->updateMany() ->field('tags')->pull('tag1') ->getQuery() ->execute();
2
3
4
5
6
7

Read more about the $pull modifier in the Mongo docs.

1<?php $dm->createQueryBuilder(Article::class) ->updateMany() ->field('tags')->pullAll(['tag1', 'tag2']) ->getQuery() ->execute();
2
3
4
5
6
7

Read more about the $pullAll modifier in the Mongo docs.

Remove Queries

In addition to updating you can also issue queries to remove documents from a collection. It works pretty much the same way as everything else and you can use the conditional operations to specify which documents you want to remove.

Here is an example where we remove users who have never logged in:

1<?php $dm->createQueryBuilder(User::class) ->remove() ->field('num_logins')->equals(0) ->getQuery() ->execute();
2
3
4
5
6
7