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
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
To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.