Overview
In this guide, you can learn how to retrieve data from MongoDB collections by using Laravel MongoDB. This guide describes the Eloquent model methods that you can use to retrieve data and provides examples of different types of find operations.
To learn more about Eloquent models in the Laravel Integration, see the Model Your Data section.
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.phpfile, which contains aMoviemodel to represent documents in themoviescollectionMovieController.phpfile, which contains ashow()function to run database operationsbrowse_movies.blade.phpfile, 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.
Tip
Retrieve One Document
The where() method retrieves all matching documents. To retrieve the first matching document, you can chain the first() method. To learn more and view an example, see the Retrieve the First Result section of this guide.
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:
yearfield has a value of2010imdb.ratingnested 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 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 the Modify Query Results 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 Query Results section of the Modify Query Output guide.
Fully Runnable Examples
The following sections provide fully runnable code examples that demonstrate how to retrieve documents by using the Laravel Integration. These examples use the sample_mflix.movies collection from the Atlas sample datasets.
Tip
You can run the full examples from your own Laravel application or from the my-app application created in the Get Started tutorial. The examples use the Movie.php model class created in this tutorial to demonstrate operations on the movies MongoDB collection. To run the operation, you can copy the sample code to a controller endpoint in your Laravel application.
To view the expected output of the operation, you can add a web route to your application that calls the controller function and returns the result to a web interface.
Find a Document
Select from the following Eloquent and Query Builder tabs to view examples for each corresponding query syntax:
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseRetrieves a document from the
moviescollection that matches a query filterPrints the retrieved document
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of thedirectorsfield includes"Rob Reiner"orderBy(): Sorts matched documents by their ascending_idvaluesfirst(): Retrieves only the first matching document
$movie = Movie::where('directors', 'Rob Reiner') ->orderBy('id') ->first(); echo $movie->toJson();
// Result is truncated { "_id": ..., "title": "This Is Spinal Tap", "directors": [ "Rob Reiner" ], ... }
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeRetrieves a document from the
moviescollection that matches a query filterPrints the
titlefield of the retrieved document
The example calls the following query builder methods:
where(): Matches documents in which the value of thedirectorsfield includes"Rob Reiner"orderBy(): Sorts matched documents by their ascending_idvaluesfirst(): Retrieves only the first matching document
$movie = DB::table('movies') ->where('directors', 'Rob Reiner') ->orderBy('_id') ->first(); echo $movie->title;
This Is Spinal Tap
Find Multiple Documents
Select from the following Eloquent and Query Builder tabs to view examples for each corresponding query syntax:
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseRetrieves and prints documents from the
moviescollection that match a query filter
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of theruntimefield is greater than900orderBy(): Sorts matched documents by their ascending_idvaluesget(): Retrieves the query results as a Laravel collection object
$movies = Movie::where('runtime', '>', 900) ->orderBy('id') ->get();
// Results are truncated [ { "_id": ..., "runtime": 1256, "title": "Centennial", ..., }, { "_id": ..., "runtime": 1140, "title": "Baseball", ..., }, ... ]
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeRetrieves and prints documents from the
moviescollection that match a query filter
The example calls the following query builder methods:
where(): Matches documents in which the value of theruntimefield is greater than900orderBy(): Sorts matched documents by their ascending_idvaluesget(): Retrieves the query results as a Laravel collection object
$movies = DB::table('movies') ->where('runtime', '>', 900) ->orderBy('_id') ->get();
// Results are truncated [ { "_id": ..., "runtime": 1256, "title": "Centennial", ..., }, { "_id": ..., "runtime": 1140, "title": "Baseball", ..., }, ... ]
Count Documents
Select from the following Eloquent and Query Builder tabs to view examples for each corresponding query syntax:
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseCounts the documents from the
moviescollection that match a query filterPrints the matching document count
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of thegenresfield includes"Biography"count(): Counts the number of matching documents and returns the count as an integer
$count = Movie::where('genres', 'Biography') ->count(); echo 'Number of documents: ' . $count;
Number of documents: 1267
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeCounts the documents from the
moviescollection that match a query filterPrints the matching document count
The example calls the following query builder methods:
where(): Matches documents in which the value of thegenresfield includes"Biography"count(): Counts the number of matching documents and returns the count as an integer
$count = DB::table('movies') ->where('genres', 'Biography') ->count(); echo 'Number of documents: ' . $count;
Number of documents: 1267
Retrieve Distinct Field Values
Select from the following Eloquent and Query Builder tabs to view examples for each corresponding query syntax:
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseRetrieves distinct field values of documents from the
moviescollection that match a query filterPrints the distinct values
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of thedirectorsfield includes"Sofia Coppola"select(): Retrieves the matching documents'imdb.ratingfield valuesdistinct(): Retrieves the unique values of the selected field and returns the list of valuesget(): Retrieves the query results
$ratings = Movie::where('directors', 'Sofia Coppola') ->select('imdb.rating') ->distinct() ->get(); echo $ratings;
[[5.6],[6.4],[7.2],[7.8]]
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeRetrieves distinct field values of documents from the
moviescollection that match a query filterPrints the distinct values
The example calls the following query builder methods:
where(): Matches documents in which the value of thedirectorsfield includes"Sofia Coppola"select(): Retrieves the matching documents'imdb.ratingfield valuesdistinct(): Retrieves the unique values of the selected field and returns the list of valuesget(): Retrieves the query results
$ratings = DB::table('movies') ->where('directors', 'Sofia Coppola') ->select('imdb.rating') ->distinct() ->get(); echo $ratings;
[5.6,6.4,7.2,7.8]
Additional Information
To learn how to insert data into MongoDB, see the Insert Documents guide.
To learn how to modify the way that the Laravel Integration returns results, see the Modify Query Results guide.