Query Builder
On this page
- Overview
- Before You Get Started
- Retrieve Matching Documents
- Where Method Example
- Logical Conditional Operations
- Ranges and Type Checks
- Text Pattern Match Example
- Retrieve Distinct Values
- Aggregations
- Modify Query Results
- Order Results Example
- Omit a Specified Number of Results Example
- Show a Subset of Fields and Array Values in the Results Example
- Paginate the Results Example
- Retrieve Data by Using MongoDB Operations
- Contains a Field Example
- Contains All Fields Example
- Match Array Size Example
- Match Data Type Example
- Match a Value Computed with Modulo Example
- Match a Regular Expression
- Run MongoDB Query API Operations Example
- Match Array Elements Example
- Specify Cursor Timeout Example
- Match Locations by Using Geospatial Operations
- Near a Position Example
- Within an Area Example
- Intersecting a Geometry Example
- Proximity Data for Nearby Matches Example
- Write Data by Using MongoDB Write Operations
- Upsert a Document Example
- Increment a Numerical Value Example
- Decrement a Numerical Value Example
- Add an Array Element Example
- Remove an Array Element Example
- Remove a Field Example
Overview
In this guide, you can learn how to use the Laravel MongoDB 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
Laravel MongoDB 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 Read Operations.
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.
Laravel MongoDB aliases the DB
method table()
as the collection()
method. Chain methods to specify commands and any constraints. Then, chain
the get()
method at the end to run the methods and retrieve the results.
The following example shows the syntax of a query builder call:
DB::collection('<collection name>') // chain methods by using the "->" object operator ->get();
Tip
Before using the DB::collection()
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 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:
$connection = DB::connection('mongodb');
This guide provides examples of the following types of query builder operations:
Before You Get Started
To run the code examples in this guide, complete the
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 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 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:
$result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', 9.3) ->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 Example
The following example shows how to chain the orWhere()
query builder method to retrieve documents from the
movies
collection that either match the year
value of 1955
or match the title
value "Back to the Future"
:
$result = DB::connection('mongodb') ->collection('movies') ->where('year', 1955) ->orWhere('title', 'Back to the Future') ->get();
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
:
$result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) ->where('year', '<', 1940) ->get();
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
:
$result = DB::connection('mongodb') ->collection('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 than8.5
year
value is either1986
or1996
$result = DB::connection('mongodb') ->collection('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:
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
:
$result = DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get();
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:
$result = DB::connection('mongodb') ->collection('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:
$result = DB::collection('movies') ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) ->get();
Match Dates Example
The following example shows how to use the whereDate()
query builder method to retrieve documents from the
movies
collection that match the specified date of
2010-1-15
in the released
field:
$result = DB::connection('mongodb') ->collection('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
$result = DB::collection('movies') ->where('title', 'like', '%spider_man%') ->get();
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.
$result = DB::collection('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 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 thewhere()
methodGroup data by the distinct values of the
runtime
field, which is assigned the_id
field, by using thegroupBy()
methodSort the groups by the
runtime
field by using theorderBy()
methodReturn
title
data from the last document in the grouped result by specifying it in theget()
method
Tip
The groupBy()
method calls the MongoDB $group
aggregation operator
and $last
accumulator operator. To learn more about these operators, see
$group (aggregation)
in the Server manual.
$result = DB::collection('movies') ->where('rated', 'G') ->groupBy('runtime') ->orderBy('runtime', 'asc') ->get(['title']);
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:
$result = DB::collection('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:
$result = DB::collection('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:
$result = DB::collection('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.
$result = DB::collection('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:
$result = DB::collection('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:
$result = DB::collection('movies') ->where('year', '>', 2000) ->avg('imdb.rating');
Modify Query Results
This section includes query builder examples for the following functions that modify the order and format of query results:
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:
$result = DB::collection('movies') ->where('title', 'like', 'back to the future%') ->orderBy('imdb.rating', 'desc') ->get();
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:
$result = DB::collection('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 existDocument
_id
field, which is automatically included
$result = DB::collection('movies') ->where('imdb.rating', '>', 8.5) ->project([ 'title' => 1, 'cast' => ['$slice' => [1, 3]], ]) ->get();
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.
$resultsPerPage = 15; $projectionFields = ['title', 'runtime', 'imdb.rating']; $result = DB::collection('movies') ->orderBy('imdb.votes', 'desc') ->paginate($resultsPerPage, $projectionFields);
To learn more about pagination, see 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 specific number of elements in an array
Match documents that contain a particular data type in a field
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
:
$result = DB::collection('movies') ->exists('random_review', true);
To learn more about this query operator, see $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 contain all the specified fields:
$result = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) ->get();
To learn more about this query operator, see $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:
$result = DB::collection('movies') ->where('directors', 'size', 5) ->get();
To learn more about this query operator, see $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.
$result = DB::collection('movies') ->where('released', 'type', 4) ->get();
To learn more about the type codes and query operator, see $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:
$result = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get();
To learn more about this query operator, see $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:
$result = DB::connection('mongodb') ->collection('movies') ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) ->get();
To learn more about regular expression queries in MongoDB, see $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:
$result = DB::collection('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:
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 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:
$result = DB::collection('movies') ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']]) ->get();
To learn more about regular expression queries in MongoDB, see the $elemMatch operator 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.
$result = DB::collection('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()
in the PHP Library documentation.
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:
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 section in the
Schema Builder guide.
To learn more about GeoJSON objects that MongoDB supports, see GeoJSON Objects 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:
$results = DB::collection('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 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:
$results = DB::collection('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:
$results = DB::collection('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:
$results = DB::collection('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 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 Example
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:
$result = DB::collection('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.
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:
$result = DB::collection('movies') ->where('title', 'Field of Dreams') ->increment('imdb.votes', 3000);
The increment()
query builder method returns the number of documents that the
operation updated.
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:
$result = DB::collection('movies') ->where('title', 'Sharknado') ->decrement('imdb.rating', 0.2);
The decrement()
query builder method returns the number of documents that the
operation updated.
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:
$result = DB::collection('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:
$result = DB::collection('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:
$result = DB::collection('movies') ->where('title', 'Final Accord') ->unset('tomatoes.viewer');
The unset()
query builder method returns the number of documents that the
operation updated.