Find a Document
You can retrieve a single document from a collection by creating a query builder, using a method such
as Model::where()
or the DB
facade to match documents in a collection, 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.
Example
This usage 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
values.first()
: retrieves only the first matching document.
$movie = Movie::where('directors', 'Rob Reiner') ->orderBy('_id') ->first(); echo $movie->toJson();
To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.
Tip
To learn more about retrieving documents with Laravel MongoDB, see the Read Operations guide.