Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

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.

This usage example performs the following actions:

  • Uses the Movie Eloquent model to represent the movies collection in the sample_mflix database

  • Retrieves a document from the movies collection that matches a query filter

  • Prints the retrieved document

The example calls the following methods on the Movie model:

  • where(): matches documents in which the value of the directors 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();
// Result is truncated
{
"_id": ...,
"title": "This Is Spinal Tap",
"directors": [ "Rob Reiner" ],
...
}

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 the Laravel Integration, see the Read Operations guide.

Back

Usage Examples