Read Operations
On this page
Overview
In this guide, you can learn how to use Laravel MongoDB to perform find operations on your MongoDB collections. Find operations allow you to retrieve documents based on criteria that you specify.
This guide shows you how to perform the following tasks:
Before You Get Started
To run the code examples in this guide, complete the Quick Start tutorial. This tutorial provides instructions on setting up a MongoDB Atlas instance with sample data and creating the following files in your Laravel web application:
Movie.php
file, which contains aMovie
model to represent documents in themovies
collectionMovieController.php
file, which contains ashow()
function to run database operationsbrowse_movies.blade.php
file, which contains HTML code to display the results of database operations
The following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output.
Retrieve Documents that Match a Query
You can use Laravel's Eloquent object-relational mapper (ORM) to create models that represent MongoDB collections and chain methods on them to specify query criteria.
To retrieve documents that match a set of criteria, call the where()
method on the collection's corresponding Eloquent model, then pass a query
filter to the method.
A query filter specifies field value requirements and instructs the find operation to return only documents that meet these requirements.
You can use one of the following where()
method calls to build a query:
where('<field name>', <value>)
builds a query that matches documents in which the target field has the exact specified valuewhere('<field name>', '<comparison operator>', <value>)
builds a query that matches documents in which the target field's value meets the comparison criteria
To apply multiple sets of criteria to the find operation, you can chain a series
of where()
methods together.
After building your query by using the where()
method, chain the get()
method to retrieve the query results.
This example calls two where()
methods on the Movie
Eloquent model to
retrieve documents that meet the following criteria:
year
field has a value of2010
imdb.rating
nested field has a value greater than8.5
Use the following syntax to specify the query:
$movies = Movie::where('year', 2010) ->where('imdb.rating', '>', 8.5) ->get();
To see the query results in the browse_movies
view, edit the show()
function
in the MovieController.php
file to resemble the following code:
class MovieController { public function show() { $movies = Movie::where('year', 2010) ->where('imdb.rating', '>', 8.5) ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Title: Inception Year: 2010 Runtime: 148 IMDB Rating: 8.8 IMDB Votes: 1294646 Plot: A thief who steals corporate secrets through use of dream-sharing technology is given the inverse task of planting an idea into the mind of a CEO. Title: Senna Year: 2010 Runtime: 106 IMDB Rating: 8.6 IMDB Votes: 41904 Plot: A documentary on Brazilian Formula One racing driver Ayrton Senna, who won the F1 world championship three times before his death at age 34.
To learn how to query by using the Laravel query builder instead of the Eloquent ORM, see the Query Builder page.
Match Array Field Elements
You can specify a query filter to match array field elements when retrieving documents. If your documents contain an array field, you can match documents based on if the value contains all or some specified array elements.
You can use one of the following where()
method calls to build a
query on an array field:
where('<array field>', <array>)
builds a query that matches documents in which the array field value is exactly the specified arraywhere('<array field>', 'in', <array>)
builds a query that matches documents in which the array field value contains one or more of the specified array elements
After building your query by using the where()
method, chain the get()
method to retrieve the query results.
Select from the following Exact Array Match and Element Match tabs to view the query syntax for each pattern:
This example retrieves documents in which the countries
array is
exactly ['Indonesia', 'Canada']
:
$movies = Movie::where('countries', ['Indonesia', 'Canada']) ->get();
This example retrieves documents in which the countries
array
contains one of the values in the array ['Canada', 'Egypt']
:
$movies = Movie::where('countries', 'in', ['Canada', 'Egypt']) ->get();
To learn how to query array fields by using the Laravel query builder instead of the Eloquent ORM, see the Match Array Elements Example section in the Query Builder guide.
Retrieve All Documents in a Collection
You can retrieve all documents in a collection by omitting the query filter.
To return the documents, call the get()
method on an Eloquent model that
represents your collection. Alternatively, you can use the get()
method's
alias all()
to perform the same operation.
Use the following syntax to run a find operation that matches all documents:
$movies = Movie::get();
Warning
The movies
collection in the Atlas sample dataset contains a large amount of data.
Retrieving and displaying all documents in this collection might cause your web
application to time out.
To avoid this issue, specify a document limit by using the take()
method. For
more information about take()
, see the Modify Behavior section of this
guide.
Search Text Fields
A text search retrieves documents that contain a term or a phrase in the text-indexed fields. A term is a sequence of characters that excludes whitespace characters. A phrase is a sequence of terms with any number of whitespace characters.
Note
Before you can perform a text search, you must create a text index on the text-valued field. To learn more about creating indexes, see the Manage Indexes section of the Schema Builder guide.
You can perform a text search by using the $text operator followed
by the $search
field in your query filter that you pass to the
where()
method. The $text
operator performs a text search on the
text-indexed fields. The $search
field specifies the text to search for.
After building your query by using the where()
method, chain the get()
method to retrieve the query results.
This example calls the where()
method on the Movie
Eloquent model to
retrieve documents in which the plot
field contains the phrase
"love story"
. To perform this text search, the collection must have
a text index on the plot
field.
Use the following syntax to specify the query:
$movies = Movie::where('$text', ['$search' => '"love story"']) ->get();
To see the query results in the browse_movies
view, edit the show()
function
in the MovieController.php
file to resemble the following code:
class MovieController { public function show() { $movies = Movie::where('$text', ['$search' => '"love story"']) ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Title: Cafè de Flore Year: 2011 Runtime: 120 IMDB Rating: 7.4 IMDB Votes: 9663 Plot: A love story between a man and woman ... Title: Paheli Year: 2005 Runtime: 140 IMDB Rating: 6.7 IMDB Votes: 8909 Plot: A folk tale - supernatural love story about a ghost ... Title: Por un puèado de besos Year: 2014 Runtime: 98 IMDB Rating: 6.1 IMDB Votes: 223 Plot: A girl. A boy. A love story ... ...
A text search assigns a numerical text score to indicate how closely
each result matches the string in your query filter. You can sort the
results by relevance by using the orderBy()
method to sort on the
textScore
metadata field. You can access this metadata by using the
$meta operator:
$movies = Movie::where('$text', ['$search' => '"love story"']) ->orderBy('score', ['$meta' => 'textScore']) ->get();
Tip
To learn more about the orderBy()
method, see the
Sort Query Results section of this guide.
Modify Behavior
You can modify the results of a find operation by chaining more methods
to where()
.
The following sections demonstrate how to modify the behavior of the where()
method:
Skip and Limit Results uses the
skip()
method to set the number of documents to skip and thetake()
method to set the total number of documents to returnSort Query Results uses the
orderBy()
method to return query results in a specified order based on field valuesReturn the First Result uses the
first()
method to return the first document that matches the query filter
Skip and Limit Results
This example queries for documents in which the year
value is 1999
.
The operation skips the first 2
matching documents and outputs a total of 3
documents.
Use the following syntax to specify the query:
$movies = Movie::where('year', 1999) ->skip(2) ->take(3) ->get();
To see the query results in the browse_movies
view, edit the show()
function
in the MovieController.php
file to resemble the following code:
class MovieController { public function show() { $movies = Movie::where('year', 1999) ->skip(2) ->take(3) ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Title: Three Kings Year: 1999 Runtime: 114 IMDB Rating: 7.2 IMDB Votes: 130677 Plot: In the aftermath of the Persian Gulf War, 4 soldiers set out to steal gold that was stolen from Kuwait, but they discover people who desperately need their help. Title: Toy Story 2 Year: 1999 Runtime: 92 IMDB Rating: 7.9 IMDB Votes: 346655 Plot: When Woody is stolen by a toy collector, Buzz and his friends vow to rescue him, but Woody finds the idea of immortality in a museum tempting. Title: Beowulf Year: 1999 Runtime: 95 IMDB Rating: 4 IMDB Votes: 9296 Plot: A sci-fi update of the famous 6th Century poem. In a besieged land, Beowulf must battle against the hideous creature Grendel and his vengeance seeking mother.
Sort Query Results
To order query results based on the values of specified fields, use the where()
method
followed by the orderBy()
method.
You can set an ascending or descending sort direction on
results. By default, the orderBy()
method sets an ascending sort on
the supplied field name, but you can explicitly specify an ascending
sort by passing "asc"
as the second parameter. To
specify a descending sort, pass "desc"
as the second parameter.
If your documents contain duplicate values in a specific field, you can handle the tie by specifying more fields to sort on. This ensures consistent results if the other fields contain unique values.
This example queries for documents in which the value of the countries
field contains
"Indonesia"
and orders results first by an ascending sort on the
year
field, then a descending sort on the title
field.
Use the following syntax to specify the query:
$movies = Movie::where('countries', 'Indonesia') ->orderBy('year') ->orderBy('title', 'desc') ->get();
To see the query results in the browse_movies
view, edit the show()
function
in the MovieController.php
file to resemble the following code:
class MovieController { public function show() { $movies = Movie::where('countries', 'Indonesia') ->orderBy('year') ->orderBy('title', 'desc') ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Title: Joni's Promise Year: 2005 Runtime: 83 IMDB Rating: 7.6 IMDB Votes: 702 Plot: A film delivery man promises ... Title: Gie Year: 2005 Runtime: 147 IMDB Rating: 7.5 IMDB Votes: 470 Plot: Soe Hok Gie is an activist who lived in the sixties ... Title: Requiem from Java Year: 2006 Runtime: 120 IMDB Rating: 6.6 IMDB Votes: 316 Plot: Setyo (Martinus Miroto) and Siti (Artika Sari Dewi) are young married couple ... ...
Tip
To learn more about sorting, see the following resources:
Natural order in the Server manual glossary
Ordering, Grouping, Limit, and Offset in the Laravel documentation
Return the First Result
To retrieve the first document that matches a set of criteria, use the where()
method
followed by the first()
method.
Chain the orderBy()
method to first()
to get consistent results when you query on a unique
value. If you omit the orderBy()
method, MongoDB returns the matching documents according to
the documents' natural order, or as they appear in the collection.
This example queries for documents in which the value of the runtime
field is
30
and returns the first matching document according to the value of the _id
field.
Use the following syntax to specify the query:
$movie = Movie::where('runtime', 30) ->orderBy('_id') ->first();
To see the query results in the browse_movies
view, edit the show()
function
in the MovieController.php
file to resemble the following code:
class MovieController { public function show() { $movie = Movie::where('runtime', 30) ->orderBy('_id') ->first(); return view('browse_movies', [ 'movies' => $movie ]); } }
Title: Statues also Die Year: 1953 Runtime: 30 IMDB Rating: 7.6 IMDB Votes: 620 Plot: A documentary of black art.
Tip
To learn more about the orderBy()
method, see the
Sort Query Results section of this guide.