Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

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.

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 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" ],
...
}

This example performs the following actions:

  • Accesses the movies collection by calling the table() method from the DB facade

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

  • Prints the title field of the retrieved document

The example calls the following query builder methods:

  • 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 = 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.

Back

Usage Examples