> This page location: /docs.md > /docs/drivers.md > /docs/languages/php.md > /docs/drivers/php/laravel-mongodb/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Query Builder

## Overview

In this guide, you can learn how to use the Laravel Integration extension of the Laravel query builder to work with a MongoDB database. The query builder lets you use a single syntax and fluent interface to write queries for any supported database.

**Note:**

The Laravel Integration extends Laravel's query builder and Eloquent ORM, which can run similar database operations. To learn more about retrieving documents by using Eloquent models, see [Query Documents.](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query.md#std-label-laravel-fundamentals-retrieve)

Laravel provides a **facade** to access the query builder class `DB`, which lets you perform database operations. Facades, which are static interfaces to classes, make the syntax more concise, avoid runtime errors, and improve testability.

The Laravel Integration provides the `DB` method `table()` to access a collection. Chain methods to specify commands and any constraints. Then, chain the `get()` method at the end to run the methods and retrieve the results. To retrieve only the first matching result, chain the `first()` method instead of the `get()` method. Starting in Laravel MongoDB v5.0, the query builder returns results as `stdClass` objects.

The following example shows the syntax of a query builder call:

```php
DB::table('<collection name>')
    // chain methods by using the "->" object operator
    ->get();
```

**Tip: Set Database Connection**

Before using the `DB::table()` method, ensure that you specify MongoDB as your application's default database connection. For instructions on setting the database connection, see the [Configure Your MongoDB Connection](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start-connect-to-mongodb) step in the Quick Start.

If MongoDB is not your application's default database, you can use the `DB::connection()` method to specify a MongoDB connection. Pass the name of the connection to the `connection()` method, as shown in the following code:

```php
$connection = DB::connection('mongodb');
```

This guide provides examples of the following types of query builder operations:

- [Retrieve Matching Documents](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-retrieve-query-builder)

- [Set Query-Level Options](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-options-query-builder)

- [Modify Query Results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-modify-results-query-builder)

- [Retrieve Data by Using MongoDB Operations](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-read-query-builder)

- [Write Data by Using MongoDB Write Operations](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-write-query-builder)

## Before You Get Started

To run the code examples in this guide, complete the [Quick Start](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start) tutorial to configure a web application, load sample datasets into your MongoDB deployment, and run the example code from a controller method. To see the expected code output as JSON documents, use the `toJson()` method shown in the optional [View your results as JSON documents](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start-json) step of the Quick Start.

To perform read and write operations by using the query builder, import the `Illuminate\Support\Facades\DB` facade and compose your query.

## Retrieve Matching Documents

This section includes query builder examples for read operations in the following operator categories:

- [Where method](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-where-example)

- [Logical conditionals](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-logical-operations)

- [Ranges and type checks](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-range-type)

- [Pattern searches](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-pattern)

- [Retrieve distinct values](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-distinct)

- [Aggregations](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregations)

### Where Method Example

The following example shows how to use the `where()` query builder method to retrieve documents from the `movies` collection that contain an `imdb.rating` field value of exactly `9.3`. Click the VIEW OUTPUT button to see the results returned by the query:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('imdb.rating', 9.3)
    ->get();
```

**Output:**

```json
[
   { "title": "Cosmos",
     "year": 1980,
     "runtime": 60,
     "imdb": {
       "rating": 9.3,
       "votes": 17174,
       "id": 81846
     },
     "plot": "Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe.",
     ...
   },
   { "title": "The Shawshank Redemption",
     "year": 1994,
     "runtime": 142,
     "imdb": {
       "rating": 9.3,
       "votes": 1521105,
       "id": 111161
     },
     "plot": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
     ...
   },
   { "title": "The Real Miyagi",
     "year": 2015,
     "runtime": 90,
     "imdb": {
       "rating": 9.3,
       "votes": 41,
       "id": 2313306
     },
     "plot": "The life of the greatest karate master of a generation.",
      ...
   }
]
```

#### Array Values

The `where()` method interprets an array value based on the following rules:

- If you pass 1 or 2 arguments to `where()`, the Laravel Integration reads an array value as a MongoDB operator document. Use this method signature to pass MongoDB query operators directly. Do not pass unvalidated user input, because MongoDB interprets the array as a query expression.

- Starting in v5.11, if you pass 3 arguments to `where()` and use the `=` operator, the Laravel Integration compares an array value as a literal document. If the value contains a MongoDB operator, the integration wraps the value in an `$eq` expression so that MongoDB compares it as a literal.

**Important:**

You cannot pass an identifier field, such as `_id`, and an operator document to the  `where()` method. If you pass these values, the Laravel Integration throws an `InvalidArgumentException`.

The following example passes an array value to the `where()` method using the 2-argument and 3-argument signatures:

```php
// 2-argument form: MongoDB applies the operator to the field
$operator = DB::connection('mongodb')
    ->table('movies')
    ->where('rated', ['$ne' => 'G'])
    ->get();

// 3-argument form: MongoDB compares the value as a literal
$literal = DB::connection('mongodb')
    ->table('movies')
    ->where('rated', '=', ['$ne' => 'G'])
    ->get();
```

### Logical Conditional Operations

The examples in this section show the query builder syntax you can use to perform the following logical conditional operations:

- [Logical OR to match one or more conditions](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-logical-or)

- [Logical AND to match all conditions](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-logical-and)

- [Logical NOT to match the negation of the condition](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-logical-not)

- [Nested logical operator groups](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-logical-nested)

#### Logical OR Example

The following example shows how to chain the `orWhere()` query builder method to retrieve documents from the `movies` collection in which the value of the `_id` field is `ObjectId('573a1398f29313caabce9682')` or the value of the `title` field is `"Back to the Future"`:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('id', new ObjectId('573a1398f29313caabce9682'))
    ->orWhere('title', 'Back to the Future')
    ->get();
```

**Note: id Alias**

You can use the `id` alias in your queries to represent the `_id` field in MongoDB documents, as shown in the preceding code. When you use the query builder to run a find operation, the Laravel Integration automatically converts between `_id` and `id` field names. In query results, the `_id` field is presented as `id`. This provides better consistency with Laravel, as the framework assumes that each record has a primary key named `id` by default.

Because of this behavior, you cannot have two separate `id` and `_id` fields in your documents.

To learn how to disable this behavior for embedded documents, see the [Disable Use of id Field Name Conversion](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connection-options.md#std-label-laravel-disable-id-alias) section of the Connection Options guide.

#### Logical AND Example

The following example shows how to chain the `where()` query builder method to retrieve documents from the `movies` collection that match both an `imdb.rating` value greater than `8.5` and a `year` value of less than `1940`:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('imdb.rating', '>', 8.5)
    ->where('year', '<', 1940)
    ->get();
```

**Tip:**

For compatibility with Laravel, Laravel MongoDB v5.1 supports both arrow (`->`) and dot (`.`) notation to access nested fields in a query filter. The preceding example uses dot notation to query the `imdb.rating` nested field, which is the recommended syntax.

#### Logical NOT Example

The following example shows how to call the `whereNot()` query builder method to retrieve documents from the `movies` collection that match documents that do not have an `imdb.rating` value greater than `2`. This is equivalent to matching all documents that have an `imdb.rating` of less than or equal to `2`:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->whereNot('imdb.rating', '>', 2)
    ->get();
```

#### Nested Logical Operator Group Example

The following example shows how to chain the `where()` query builder method to retrieve documents from the `movies` collection that match both of the following conditions. This example passes a closure as the first parameter of the `where()` query builder method to group the logical OR group:

- `imdb.rating` value is greater than `8.5`

- `year` value is either `1986` or `1996`

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('imdb.rating', '>', 8.5)
    ->where(function (Builder $query) {
        return $query
            ->where('year', 1986)
            ->orWhere('year', 1996);
    })->get();
```

### Ranges and Type Checks

The examples in this section show the query builder syntax you can use to match values by using the following range queries and type check operations:

- [Values within a numerical range](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-wherebetween)

- [Null or missing values](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-null)

- [One or more values of a set](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-wherein)

- [Match dates](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-wheredate)

- [Match a text pattern](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-pattern)

#### Numerical Range Example

The following example shows how to use the `whereBetween()` query builder method to retrieve documents from the `movies` collection that contain an `imdb.rating` value between `9` and `9.5`:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->whereBetween('imdb.rating', [9, 9.5])
    ->get();
```

**Output:**

```none
[
   { "title" "The Godfather", "imdb": { "rating": 9.2, "votes": 1038358, "id": 68646 }, ... },
   { "title": "Hollywood", "imdb": { "rating": 9.1, "votes": 511,"id": 80230 }, ... },
   { "title": "Cosmos", "imdb": { "rating": 9.3, "votes": 17174, "id": 81846 }, ... },
   ...
]
```

#### Null or Missing Values Example

The following example shows how to use the `whereNull()` query builder method to retrieve documents from the `movies` collection that omit a `runtime` value or field:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->whereNull('runtime')
    ->get();
```

#### One or More Values of a Set Example

The following example shows how to use the `whereIn()` query builder method to retrieve documents from the `movies` collection that match at least one of the `title` values in the specified set:

```php
$result = DB::table('movies')
    ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English'])
    ->get();
```

**Output:**

```json
[
   { "title": "Toy Story", "year": 1995, "runtime": 81, ... },
   { "title": "Johnny English", "year": 2003, "runtime": 87, ... },
   { "title": "Shrek 2", "year" 2004, "runtime": 93, ... },
   ...
]
```

#### Match Dates Example

The following example shows how to use the `where()` query builder method to retrieve documents from the `movies` collection in which the `released` value is January 15, 2010, specified in a `Carbon` object:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('released', Carbon::create(2010, 1, 15))
    ->get();
```

**Note: Date Query Filter and Result Type**

Starting in Laravel MongoDB v5.0, [Carbon](https://carbon.nesbot.com/) objects passed as query filters, as shown in the preceding code, are converted to `UTCDateTime` BSON values.

In query results, `UTCDateTime` BSON values in MongoDB are returned as `Carbon` objects. The Laravel Integration applies the default timezone when performing this conversion.

If you want to represent a date as a string in your query filter rather than as a `Carbon` object, use the `whereDate()` query builder method. The following example retrieves documents from the `movies` collection in which the `released` value is January 15, 2010 and specifies the date as a string:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->whereDate('released', '2010-1-15')
    ->get();
```

### Text Pattern Match Example

The following example shows how to use the `like` query operator with the `where()` query builder method to retrieve documents from the `movies` collection by using a specified text pattern.

Text patterns can contain text mixed with the following wildcard characters:

- `%` which matches zero or more characters

- `_` which matches a single character

```php
$result = DB::table('movies')
    ->where('title', 'like', '%spider_man%')
    ->get();
```

**Output:**

```json
[
   { "title": "Kiss of the Spider Woman", ... },
   { "title": "Spider-Man", ... },
   { "title": "Spider-Man 2", ...},
   ...
]
```

#### whereLike() and whereNotLike() Methods

The following methods provide the same functionality as using the [like](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-pattern) query operator to match patterns:

- `whereLike()`: Matches a specified pattern. By default, this method performs a case-insensitive match. You can enable case-sensitivity by passing `true` as the last parameter to the method.

- `whereNotLike()`: Matches documents in which the field value does not contain the specified string pattern.

The following example shows how to use the `whereLike()` method to match documents in which the `title` field has a value that matches the pattern `'Start%'` with case-sensitivity enabled:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->whereLike('title', 'Start%', true)
    ->get();
```

**Output:**

```json
[
   { "title": "Start-Up", ... },
   { "title": "Start the Revolution Without Me", ... },
   ...
]
```

### Retrieve Distinct Values

The following example shows how to use the `distinct()` query builder method to retrieve all the different values of the `year` field for documents in the `movies` collections.

```php
$result = DB::table('movies')
    ->distinct('year')->get();
```

## Aggregations

The examples in this section show the query builder syntax you can use to perform **aggregations**. Aggregations are operations that compute values from a set of query result data. You can use aggregations to compute and return the following information:

- [Results grouped by common field values](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-groupby)

- [Count the number of results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-count)

- [Maximum value of a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-max)

- [Minimum value of a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-min)

- [Average value of a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-avg)

- [Summed value of a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregation-sum)

- [Aggregate matched results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-aggregate-matched)

### Results Grouped by Common Field Values Example

The following example shows how to use the `groupBy()` query builder method to retrieve document data grouped by shared values of the `runtime` field. This example chains the following operations to match documents from the `movies` collection that contain a `rated` value of `G` and include the `title` field of one movie for each distinct `runtime` value:

- Match only documents that contain a `rated` field value of `"G"` by using the `where()` method

- Group data by the distinct values of the `runtime` field, which is assigned the `_id` field, by using the `groupBy()` method

- Sort the groups by the `runtime` field by using the `orderBy()` method

- Return `title` data from the last document in the grouped result by specifying it in the `get()` method

**Tip:**

The `groupBy()` method calls the MongoDB `$group` aggregation operator and `$last` accumulator operator. To learn more about these operators, see [$group (aggregation)](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group/) in the Server manual.

```php
$result = DB::table('movies')
    ->where('rated', 'G')
    ->groupBy('runtime')
    ->orderBy('runtime', 'asc')
    ->get(['title']);
```

**Output:**

```json
[
  ...
  {
    "_id": { "runtime": 64 },
    "runtime": 64,
    "title": "Stitch! The Movie"
  },
  {
     "_id": { "runtime": 67 },
     "runtime": 67,
     "title": "Bartok the Magnificent"
   },
   {
     "_id": { "runtime":68 },
     "runtime": 68,
     "title": "Mickey's Twice Upon a Christmas"
   },
   ...
]
```

### Number of Results Example

The following example shows how to use the `count()` query builder method to return the number of documents contained in the `movies` collection:

```php
$result = DB::table('movies')
    ->count();
```

### Maximum Value of a Field Example

The following example shows how to use the `max()` query builder method to return the highest numerical value of the `runtime` field from the entire `movies` collection:

```php
$result = DB::table('movies')
    ->max('runtime');
```

### Minimum Value of a Field Example

The following example shows how to use the `min()` query builder method to return the lowest numerical value of the `year` field from the entire `movies` collection:

```php
$result = DB::table('movies')
    ->min('year');
```

### Average Value of a Field Example

The following example shows how to use the `avg()` query builder method to return the numerical average, or arithmetic mean, of the `imdb.rating` values from the entire `movies` collection.

```php
$result = DB::table('movies')
    ->avg('imdb.rating');
```

### Summed Value of a Field Example

The following example shows how to use the `sum()` query builder method to return the numerical total of the `imdb.votes` values from the entire `movies` collection:

```php
$result = DB::table('movies')
    ->sum('imdb.votes');
```

### Aggregate Matched Results Example

The following example shows how to aggregate data from results that match a query. The query matches all movies after the year `2000` and computes the average value of `imdb.rating` of those matches by using the `avg()` method:

```php
$result = DB::table('movies')
    ->where('year', '>', 2000)
    ->avg('imdb.rating');
```

## Set Query-Level Options

You can modify the way that the Laravel Integration performs operations by setting options on the query builder. You can pass an array of options to the `options()` query builder method to specify options for the query.

The following code demonstrates how to attach a comment to a query:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('year', 2000)
    ->options(['comment' => 'hello'])
    ->get();
```

The query builder accepts the same options that you can set for the [`find()`](https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-find.md#mongodb-phpmethod-phpmethod.MongoDB-Collection--find--) method in the MongoDB PHP Library. Some of the options to modify query results, such as `skip`, `sort`, and `limit`, are settable directly as query builder methods and are described in the [Modify Query Results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-modify-results-query-builder) section of this guide. We recommend that you use these methods instead of passing them as options.

## Modify Query Results

This section includes query builder examples for the following functions that modify the order and format of query results:

- [Order results by the value of a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-orderby)

- [Omit a specified number of results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-skip)

- [Show a subset of fields and array values in the results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-project)

- [Paginate the results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-paginate)

### Order Results Example

The following example shows how to use the `orderBy()` query builder method to arrange the results that match the filter specified in the `title` field by the `imdb.rating` value in descending order:

```php
$result = DB::table('movies')
    ->where('title', 'like', 'back to the future%')
    ->orderBy('imdb.rating', 'desc')
    ->get();
```

**Output:**

```json
[
  { "title": "Back to the Future", "imdb": { "rating":8.5,"votes":636511,"id":88763 }, ... },
  { "title": "Back to the Future Part II", "imdb": { "rating":7.8,"votes":292539,"id":96874 }, ... },
  { "title": "Back to the Future Part III", "imdb": {"rating":7.4,"votes":242390,"id":99088 }, ... },
  ...
]
```

### Omit a Specified Number of Results Example

The following example shows how to use the `skip()` query builder method to omit the first four results that match the filter specified in the `title` field, sorted by the `year` value in ascending order:

```php
$result = DB::table('movies')
    ->where('title', 'like', 'star trek%')
    ->orderBy('year', 'asc')
    ->skip(4)
    ->get();
```

### Show a Subset of Fields and Array Values in the Results Example

The following example shows how to use the `project()` query builder method to match documents that contain an `imdb.rating` value higher than `8.5` and return only the following field values:

- Title of the movie in the `title`

- Second through fourth values of the `cast` array field, if they exist

- Document `_id` field, which is automatically included

```php
$result = DB::table('movies')
    ->where('imdb.rating', '>', 8.5)
    ->project([
        'title' => 1,
        'cast' => ['$slice' => [1, 3]],
    ])
    ->get();
```

**Output:**

```json
[
  {
    "_id": { ... },
    "title": "City Lights"
    "cast": [
      "Florence Lee",
      "Harry Myers",
      "Al Ernest Garcia"
    ],
  },
  {
    "_id": { ... },
    "title": "Modern Times",
    "cast": [
      "Paulette Goddard",
      "Henry Bergman",
      "Tiny Sandford"
    ]
  },
  {
    "_id": { ... },
    "title": "Casablanca"
    "cast": [
      "Ingrid Bergman",
      "Paul Henreid",
      "Claude Rains"
    ],
  },
  ...
]
```

### Paginate the Results Example

The following example shows how to use the `paginate()` query builder method to divide the entire `movie` collection into discrete result sets of 15 documents. The example also includes a sort order to arrange the results by the `imdb.votes` field in descending order and a projection that includes only specific fields in the results.

```php
$resultsPerPage = 15;
$projectionFields = ['title', 'runtime', 'imdb.rating'];

$result = DB::table('movies')
    ->orderBy('imdb.votes', 'desc')
    ->paginate($resultsPerPage, $projectionFields);
```

To learn more about pagination, see [Paginating Query Builder Results](https://laravel.com/docs/12.x/pagination#paginating-query-builder-results) in the Laravel documentation.

## Retrieve Data by Using MongoDB Operations

This section includes query builder examples that show how to use the following MongoDB-specific query operations:

- [Match documents that contain a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-exists)

- [Match documents that contain all specified fields](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-all)

- [Match documents that contain a specific number of elements in an array](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-size)

- [Match documents that contain a particular data type in a field](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-type)

- [Match documents that contain a computed modulo value](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-mod)

- [Match documents that match a regular expression](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-regex)

- [Run MongoDB Query API operations](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-whereRaw)

- [Match documents that contain array elements](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-elemMatch)

- [Specify a cursor timeout](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-cursor-timeout)

- [Specify a read preference](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-read-pref)

- [Match locations by using geospatial searches](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-geospatial)

### Contains a Field Example

The following example shows how to use the `exists()` query builder method to match documents that contain the field `random_review`:

```php
$result = DB::table('movies')
    ->exists('random_review', true);
```

To learn more about this query operator, see [$exists](https://www.mongodb.com/docs/manual/reference/operator/query/exists/) in the Server manual.

### Contains All Fields Example

The following example shows how to use the `all` query operator with the `where()` query builder method to match documents that have a `writers` array field containing all the specified values:

```php
$result = DB::table('movies')
    ->where('writers', 'all', ['Ben Affleck', 'Matt Damon'])
    ->get();
```

To learn more about this query operator, see [$all](https://www.mongodb.com/docs/manual/reference/operator/query/all/) in the Server manual.

### Match Array Size Example

The following example shows how to pass the `size` query operator with the `where()` query builder method to match documents that contain a `directors` field that contains an array of exactly five elements:

```php
$result = DB::table('movies')
    ->where('directors', 'size', 5)
    ->get();
```

To learn more about this query operator, see [$size](https://www.mongodb.com/docs/manual/reference/operator/query/size/) in the Server manual.

### Match Data Type Example

The following example shows how to pass the `type` query operator with the `where()` query builder method to match documents that contain a type `4` value, which corresponds to an array data type, in the `released` field.

```php
$result = DB::table('movies')
    ->where('released', 'type', 4)
    ->get();
```

To learn more about the type codes and query operator, see [$type](https://www.mongodb.com/docs/manual/reference/operator/query/type/) in the Server manual.

### Match a Value Computed with Modulo Example

The following example shows how to pass the `mod` query operator with the `where()` query builder method to match documents by using the expression `year % 2 == 0`, which matches even values for the `year` field:

```php
$result = DB::table('movies')
    ->where('year', 'mod', [2, 0])
    ->get();
```

To learn more about this query operator, see [$mod](https://www.mongodb.com/docs/manual/reference/operator/query/mod/) in the Server manual.

### Match a Regular Expression

The following example shows how to pass the `REGEX` query operator with the `where()` query builder method to match documents that contain a `title` field that matches the specified regular expression:

```php
$result = DB::connection('mongodb')
    ->table('movies')
    ->where('title', 'REGEX', new Regex('^the lord of .*', 'i'))
    ->get();
```

To learn more about regular expression queries in MongoDB, see [$regex](https://www.mongodb.com/docs/manual/reference/operator/query/regex/) in the Server manual.

### Run MongoDB Query API Operations Example

The following example shows how to use the `whereRaw()` query builder method to run a query operation written by using the MongoDB Query API syntax:

```php
$result = DB::table('movies')
    ->whereRaw([
        'imdb.votes' => ['$gte' => 1000],
        '$or' => [
            ['imdb.rating' => ['$gt' => 7]],
            ['directors' => ['$in' => ['Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini']]],
        ],
    ])->get();
```

The following code shows the equivalent MongoDB Query API syntax:

```text
db.movies.find({
  "imdb.votes": { $gte: 1000 },
  $or: [{
    imdb.rating: { $gt: 7 },
    directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] }
}]});
```

To learn more about the MongoDB Query API, see [MongoDB Query API](https://www.mongodb.com/docs/manual/query-api/) in the Server manual.

### Match Array Elements Example

The following example shows how to pass the `elemMatch` query operator with the `where()` query builder method to match documents that contain an array element that matches at least one of the conditions in the specified query:

```php
$result = DB::table('movies')
    ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']])
    ->get();
```

To learn more about regular expression queries in MongoDB, see the [$elemMatch operator](https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/) in the Server manual.

### Specify Cursor Timeout Example

The following example shows how to use the `timeout()` method to specify a maximum duration to wait for cursor operations to complete.

```php
$result = DB::table('movies')
    ->timeout(2) // value in seconds
    ->where('year', 2001)
    ->get();
```

**Note:**

This setting specifies a `maxTimeMS` value in seconds instead of milliseconds. To learn more about the `maxTimeMS` value, see [MongoDBCollection::find()](https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-find/) in the PHP Library documentation.

### Specify a Read Preference Example

You can control how the Laravel Integration directs read operations to replica set members by setting a read preference.

The following example queries the `movies` collection for documents in which the `runtime` value is greater than `240`. The example passes a value of `ReadPreference::SECONDARY_PREFERRED` to the `readPreference()` method, which sends the query to secondary replica set members or the primary member if no secondaries are available:

```php
$result = DB::table('movies')
    ->where('runtime', '>', 240)
    ->readPreference(ReadPreference::SECONDARY_PREFERRED)
    ->get();
```

**Tip:**

To learn more about read preferences, see [Read Preference](https://www.mongodb.com/docs/manual/core/read-preference/) in the MongoDB Server manual.

### Match Locations by Using Geospatial Operations

The examples in this section show the query builder syntax you can use to perform geospatial queries on GeoJSON or coordinate pair data to retrieve the following types of locations:

- [Near a position](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-geospatial-near)

- [Within a the boundary of a GeoJSON object](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-geospatial-geoWithin)

- [Intersecting a GeoJSON object](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-geospatial-geoIntersects)

- [Proximity data for nearby matches](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-query-builder-geospatial-geoNear)

**Important:**

To perform GeoJSON queries in MongoDB, you must create either `2d` or `2dsphere` index on the collection. To learn how to create geospatial indexes, see the [Create a Geospatial Index](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/schema-builder.md#std-label-laravel-eloquent-geospatial-index) section in the Schema Builder guide.

To learn more about GeoJSON objects that MongoDB supports, see [GeoJSON Objects](https://www.mongodb.com/docs/manual/reference/geojson/) in the Server manual.

#### Near a Position Example

The following example shows how to use the `near` query operator with the `where()` query builder method to match documents that contain a location that is up to `50` meters from a GeoJSON Point object:

```php
$results = DB::table('theaters')
    ->where('location.geo', 'near', [
        '$geometry' => [
            'type' => 'Point',
            'coordinates' => [
                -86.6423,
                33.6054,
            ],
        ],
        '$maxDistance' => 50,
    ])->get();
```

To learn more about this operator, see [$near operator](https://www.mongodb.com/docs/manual/reference/operator/query/near/) in the Server manual.

#### Within an Area Example

The following example shows how to use the `geoWithin` query operator with the `where()` query builder method to match documents that contain a location within the bounds of the specified `Polygon` GeoJSON object:

```php
$results = DB::table('theaters')
    ->where('location.geo', 'geoWithin', [
        '$geometry' => [
            'type' => 'Polygon',
            'coordinates' => [
                [
                    [-72, 40],
                    [-74, 41],
                    [-72, 39],
                    [-72, 40],
                ],
            ],
        ],
    ])->get();
```

#### Intersecting a Geometry Example

The following example shows how to use the `geoInstersects` query operator with the `where()` query builder method to match documents that contain a location that intersects with the specified `LineString` GeoJSON object:

```php
$results = DB::table('theaters')
    ->where('location.geo', 'geoIntersects', [
        '$geometry' => [
            'type' => 'LineString',
            'coordinates' => [
                [-73.600525, 40.74416],
                [-72.600525, 40.74416],
            ],
        ],
    ])->get();
```

#### Proximity Data for Nearby Matches Example

The following example shows how to use the `geoNear` aggregation operator with the `raw()` query builder method to perform an aggregation that returns metadata, such as proximity information for each match:

```php
$results = DB::table('theaters')->raw(
    function (Collection $collection) {
        return $collection->aggregate([
            [
                '$geoNear' => [
                    'near' => [
                        'type' => 'Point',
                        'coordinates' => [-118.34, 34.10],
                    ],
                    'distanceField' => 'dist.calculated',
                    'maxDistance' => 500,
                    'includeLocs' => 'dist.location',
                    'spherical' => true,
                ],
            ],
        ]);
    },
)->toArray();
```

To learn more about this aggregation operator, see [$geoNear operator](https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/) in the Server manual.

## Write Data by Using MongoDB Write Operations

This section includes query builder examples that show how to use the following MongoDB-specific write operations:

- [Upsert a document](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-upsert)

- [Multiply and divide values](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-mul-div)

- [Increment a numerical value](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-increment)

- [Decrement a numerical value](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-decrement)

- [Add an array element](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-push)

- [Remove a value from an array](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-pull)

- [Remove a field from a document](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-mongodb-query-builder-unset)

### Upsert a Document Example

Starting in v4.7, you can perform an upsert operation by using either of the following query builder methods:

- `upsert()`: When you use this method, you can perform a **batch
  upsert** to change or insert multiple documents in one operation.

- `update()`: When you use this method, you must specify the `upsert` option to update all documents that match the query filter or insert one document if no documents are matched. Only this upsert method is supported in versions v4.6 and earlier.

#### Upsert Method

The `upsert(array $values, array|string $uniqueBy, array|null
$update)` query builder method accepts the following parameters:

- `$values`: Array of fields and values that specify documents to update or insert.

- `$uniqueBy`: List of fields that uniquely identify documents in your first array parameter.

- `$update`: Optional list of fields to update if a matching document exists. If you omit this parameter, the Laravel Integration updates all fields.

The following example shows how to use the `upsert()` query builder method to update or insert documents based on the following instructions:

- Specify a document in which the value of the `title` field is `'Inspector Maigret'`, the value of the `recommended` field is `false`, and the value of the `runtime` field is `128`.

- Specify a document in which the value of the `title` field is `'Petit Maman'`, the value of the `recommended` field is `true`, and the value of the `runtime` field is `72`.

- Indicate that the `title` field uniquely identifies documents in the scope of your operation.

- Update only the `recommended` field in matched documents.

```php
$result = DB::table('movies')
    ->upsert(
        [
            ['title' => 'Inspector Maigret', 'recommended' => false, 'runtime' => 128],
            ['title' => 'Petit Maman', 'recommended' => true, 'runtime' => 72],
        ],
        'title',
        'recommended',
    );
```

The `upsert()` query builder method returns the number of documents that the operation updated, inserted, and modified.

**Note:**

The `upsert()` method does not trigger events. To trigger events from an upsert operation, you can use the `createOrFirst()` method instead.

#### Update Method

The following example shows how to use the `update()` query builder method and `upsert` option to update the matching document or insert one with the specified data if it does not exist. When you set the `upsert` option to `true` and the document does not exist, the command inserts both the data and the `title` field and value specified in the `where()` query operation:

```php
$result = DB::table('movies')
    ->where('title', 'Will Hunting')
    ->update(
        [
            'plot' => 'An autobiographical movie',
            'year' => 1998,
            'writers' => ['Will Hunting'],
        ],
        ['upsert' => true],
    );
```

The `update()` query builder method returns the number of documents that the operation updated or inserted.

### Multiply and Divide Numerical Values Example

Starting in Laravel Integration v5.5, you can perform multiplication and division operations on numerical values by using the `multiply()` and `divide()` query builder methods.

The following example shows how to use the `multiply()` and `divide()` methods to manipulate the values of the `imdb.votes` and `runtime` fields:

```php
$result = DB::table('movies')
    ->where('year', 2001)
    ->multiply('imdb.votes', 5);

$result = DB::table('movies')
    ->where('year', 2001)
    ->divide('runtime', 2);
```

**Tip: update() Method**

You can perform the same operations by using the `update()` method and passing an update document that includes the [$mul](https://www.mongodb.com/docs/manual/reference/operator/update/mul/) operator. To learn more about `update()`, see the [Update Documents](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify.md#std-label-laravel-fundamentals-write-modify) guide.

You can optionally pass an array parameter to perform a `$set` update in the same operation, as shown in the following example:

```php
$result = DB::table('movies')
    ->where('year', 1958)
    ->multiply('runtime', 1.5, ['note' => 'Adds recovered footage.']);
```

### Increment a Numerical Value Example

The following example shows how to use the `increment()` query builder method to add `3000` to the value of the `imdb.votes` field in the matched document:

```php
$result = DB::table('movies')
    ->where('title', 'Field of Dreams')
    ->increment('imdb.votes', 3000);
```

The `increment()` query builder method returns the number of documents that the operation updated.

Starting in Laravel Integration v4.8, you can also use the `incrementEach()` query builder method to increment multiple values in a single operation. The following example uses the `incrementEach()` method to increase the values of the `awards.wins` and `imdb.votes` fields in the matched document:

```php
$result = DB::table('movies')
    ->where('title', 'Lost in Translation')
    ->incrementEach([
        'awards.wins' => 2,
        'imdb.votes' => 1050,
    ]);
```

**Note:**

If you pass a field to the `increment()` or `incrementEach()` method that has no value or doesn't exist in the matched documents, these methods initialize the specified field to the increment value.

### Decrement a Numerical Value Example

The following example shows how to use the `decrement()` query builder method to subtract `0.2` from the value of the `imdb.rating` field in the matched document:

```php
$result = DB::table('movies')
    ->where('title', 'Sharknado')
    ->decrement('imdb.rating', 0.2);
```

The `decrement()` query builder method returns the number of documents that the operation updated.

Starting in Laravel Integration v4.8, you can also use the `decrementEach()` query builder method to decrement multiple values in a single operation. The following example uses the `decrementEach()` method to decrease the values of the `metacritic` and `imdb.rating` fields in the matched document:

```php
$result = DB::table('movies')
    ->where('title', 'Dunkirk')
    ->decrementEach([
        'metacritic' => 1,
        'imdb.rating' => 0.4,
    ]);
```

**Note:**

If you pass a field to the `decrement()` or `decrementEach()` method that has no value or doesn't exist in the matched documents, these methods initialize the specified field to the decrement value.

### Add an Array Element Example

The following example shows how to use the `push()` query builder method to add `"Gary Cole"` to the `cast` array field in the matched document:

```php
$result = DB::table('movies')
    ->where('title', 'Office Space')
    ->push('cast', 'Gary Cole');
```

The `push()` query builder method returns the number of documents that the operation updated.

### Remove an Array Element Example

The following example shows how to use the `pull()` query builder method to remove the `"Adventure"` value from the `genres` field from the document matched by the query:

```php
$result = DB::table('movies')
    ->where('title', 'Iron Man')
    ->pull('genres', 'Adventure');
```

The `pull()` query builder method returns the number of documents that the operation updated.

### Remove a Field Example

The following example shows how to use the `unset()` query builder method to remove the `tomatoes.viewer` field and value from the document matched by the query:

```php
$result = DB::table('movies')
    ->where('title', 'Final Accord')
    ->unset('tomatoes.viewer');
```

The `unset()` query builder method returns the number of documents that the operation updated.
