Find a Document
You can retrieve a single document from a collection by using a method such as Model::where()
or
methods from the DB
facade to match documents, and then calling
the first()
method to return one document.
If multiple documents match the query filter, first()
returns the
first matching document according to the documents' natural order in the database or according to the sort order that you can
specify by using the orderBy()
method.
Tip
To learn about other ways to retrieve documents with the Laravel Integration, see the Read Operations guide.
Example
Select from the following Eloquent and Query Builder tabs to view usage examples for the same operation that use each corresponding query syntax:
This example performs the following actions:
Uses the
Movie
Eloquent model to represent themovies
collection in thesample_mflix
databaseRetrieves a document from the
movies
collection 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 thedirectors
field includes"Rob Reiner"
orderBy()
: Sorts matched documents by their ascending_id
valuesfirst()
: 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
movies
collection by calling thetable()
method from theDB
facadeRetrieves a document from the
movies
collection that matches a query filterPrints the
title
field of the retrieved document
The example calls the following query builder methods:
where()
: Matches documents in which the value of thedirectors
field includes"Rob Reiner"
orderBy()
: Sorts matched documents by their ascending_id
valuesfirst()
: Retrieves only the first matching document
$movie = DB::table('movies') ->where('directors', 'Rob Reiner') ->orderBy('_id') ->first(); echo $movie->title;
This Is Spinal Tap
To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.