Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Read Operations

On this page

  • Overview
  • Before You Get Started
  • Retrieve Documents that Match a Query
  • Retrieve All Documents in a Collection
  • Search Text Fields
  • Modify Behavior
  • Skip and Limit Results
  • Sort Query Results
  • Return the First Result

In this guide, you can learn how to use Laravel MongoDB to perform find operations on your MongoDB collections. Find operations allow you to retrieve documents based on criteria that you specify.

This guide shows you how to perform the following tasks:

  • Retrieve Documents that Match a Query

  • Retrieve All Documents in a Collection

  • Search Text Fields

  • Modify Find Operation Behavior

To run the code examples in this guide, complete the Quick Start tutorial. This tutorial provides instructions on setting up a MongoDB Atlas instance with sample data and creating the following files in your Laravel web application:

  • Movie.php file, which contains a Movie model to represent documents in the movies collection

  • MovieController.php file, which contains a show() function to run database operations

  • browse_movies.blade.php file, which contains HTML code to display the results of database operations

The following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output.

You can use Laravel's Eloquent object-relational mapper (ORM) to create models that represent MongoDB collections and chain methods on them to specify query criteria.

To retrieve documents that match a set of criteria, pass a query filter to the where() method.

A query filter specifies field value requirements and instructs the find operation to return only documents that meet these requirements.

You can use Laravel's Eloquent object-relational mapper (ORM) to create models that represent MongoDB collections. To retrieve documents from a collection, call the where() method on the collection's corresponding Eloquent model.

You can use one of the following where() method calls to build a query:

  • where('<field name>', <value>) builds a query that matches documents in which the target field has the exact specified value

  • where('<field name>', '<comparison operator>', <value>) builds a query that matches documents in which the target field's value meets the comparison criteria

To apply multiple sets of criteria to the find operation, you can chain a series of where() methods together.

After building your query with the where() method, chain the get() method to retrieve the query results.

This example calls two where() methods on the Movie Eloquent model to retrieve documents that meet the following criteria:

  • year field has a value of 2010

  • imdb.rating nested field has a value greater than 8.5

To learn how to query by using the Laravel query builder instead of the Eloquent ORM, see the Query Builder page.

You can retrieve all documents in a collection by omitting the query filter. To return the documents, call the get() method on an Eloquent model that represents your collection. Alternatively, you can use the get() method's alias all() to perform the same operation.

Use the following syntax to run a find operation that matches all documents:

$movies = Movie::get();

Warning

The movies collection in the Atlas sample dataset contains a large amount of data. Retrieving and displaying all documents in this collection might cause your web application to time out.

To avoid this issue, specify a document limit by using the take() method. For more information about take(), see the Modify Behavior section of this guide.

A text search retrieves documents that contain a term or a phrase in the text-indexed fields. A term is a sequence of characters that excludes whitespace characters. A phrase is a sequence of terms with any number of whitespace characters.

Note

Before you can perform a text search, you must create a text index on the text-valued field. To learn more about creating indexes, see the Manage Indexes section of the Schema Builder guide.

You can perform a text search by using the $text operator followed by the $search field in your query filter that you pass to the where() method. The $text operator performs a text search on the text-indexed fields. The $search field specifies the text to search for.

After building your query with the where() method, chain the get() method to retrieve the query results.

This example calls the where() method on the Movie Eloquent model to retrieve documents in which the plot field contains the phrase "love story". To perform this text search, the collection must have a text index on the plot field.

A text search assigns a numerical text score to indicate how closely each result matches the string in your query filter. You can sort the results by relevance by using the orderBy() method to sort on the textScore metadata field. You can access this metadata by using the $meta operator:

$movies = Movie::where('$text', ['$search' => '"love story"'])
->orderBy('score', ['$meta' => 'textScore'])
->get();

Tip

To learn more about the orderBy() method, see the Sort Query Results section of this guide.

You can modify the results of a find operation by chaining more methods to where().

The following sections demonstrate how to modify the behavior of the where() method:

  • Skip and Limit Results uses the skip() method to set the number of documents to skip and the take() method to set the total number of documents to return

  • Sort Query Results uses the orderBy() method to return query results in a specified order based on field values

  • Return the First Result uses the first() method to return the first document that matches the query filter

This example queries for documents in which the year value is 1999. The operation skips the first 2 matching documents and outputs a total of 3 documents.

To order query results based on the values of specified fields, use the where() method followed by the orderBy() method.

You can set an ascending or descending sort direction on results. By default, the orderBy() method sets an ascending sort on the supplied field name, but you can explicitly specify an ascending sort by passing "asc" as the second parameter. To specify a descending sort, pass "desc" as the second parameter.

If your documents contain duplicate values in a specific field, you can handle the tie by specifying more fields to sort on. This ensures consistent results if the other fields contain unique values.

This example queries for documents in which the value of the countries field contains "Indonesia" and orders results first by an ascending sort on the year field, then a descending sort on the title field.

Tip

To learn more about sorting, see the following resources:

To retrieve the first document that matches a set of criteria, use the where() method followed by the first() method.

Chain the orderBy() method to first() to get consistent results when you query on a unique value. If you omit the orderBy() method, MongoDB returns the matching documents according to the documents' natural order, or as they appear in the collection.

This example queries for documents in which the value of the runtime field is 30 and returns the first matching document according to the value of the _id field.

Tip

To learn more about the orderBy() method, see the Sort Query Results section of this guide.

← Databases and Collections