Find Documents in MongoDB Using PHP

One of the important tasks is retrieving documents from a collection. MongoDB help us to make this process, but understanding how to use PHP to query your database is important. Below, we will explain everything you need to know about finding documents in MongoDB using PHP, with a strong focus on code and detailed explanations.

Finding Documents with find()

The find() method retrieves multiple documents based on a query filter. Here is an example:

$filter = ['status' => 'active'];
$options = [
    'projection' => ['_id' => 0, 'name' => 1, 'email' => 1],
    'sort' => ['name' => 1]
];

$documents = $collection->find($filter, $options);

foreach ($documents as $document) {
    print_r($document);
}
  • $filter: Specifies the criteria for selecting documents. In this case, it retrieves documents where the status field is active.
  • $options: Allows customization of the query. Here:'projection': Limits the fields returned, excluding _id and including name and email.'sort': Orders the results by name in ascending order.
  • 'projection': Limits the fields returned, excluding _id and including name and email.
  • 'sort': Orders the results by name in ascending order.
  • $collection->find(): Executes the query.
  • The foreach loop iterates through the results and prints each document.

In the following section, you will learn how to get only one document from database using MongoDB in PHP.

Finding a Single Document with findOne()

If you only need one document, use findOne():

$filter = ['email' => '[email protected]'];

document = $collection->findOne($filter);
print_r($document);
  • This retrieves the first document where the email matches the given value.
  • Unlike find()findOne() does not require a loop since it returns a single document.

Comparison Operators

MongoDB supports advanced queries with operators like $gt (greater than), $lt (less than), $in, etc. Here is an example:

$filter = [
    'age' => ['$gt' => 18],
    'status' => ['$in' => ['active', 'pending']]
];

$options = ['sort' => ['age' => -1]];

$documents = $collection->find($filter, $options);

foreach ($documents as $document) {
    print_r($document);
}
  • $gt: Matches documents where age is greater than 18.
  • $in: Matches documents where status is either active or pending.
  • The sort option orders results by age in descending order.

Limiting and Skipping Results

To control the number of documents retrieved, use limit and skip:

<?php
$filter = [];
$options = [
    'limit' => 5,
    'skip' => 10
];

$documents = $collection->find($filter, $options);

foreach ($documents as $document) {
    print_r($document);
}
?>
  • limit: Retrieves up to 5 documents.
  • skip: Skips the first 10 documents before starting to retrieve results.

Counting Documents

If you want to count the number of documents matching a query, use countDocuments():

$filter = ['status' => 'active'];

$count = $collection->countDocuments($filter);
echo "Total active documents: $count";

Let’s simmarize it.

Wrapping Up

Retrieving documents from a MongoDB collection is one of the important tasks when working with databases. With MongoDB, the process is streamlined, but using PHP to query your database requires a clear understanding of the methods and options available.

Let’s recap the points covered in this tutorial:

  • Setting Up:Before diving into queries, it is crucial to establish a connection to your MongoDB server. This setup lays the foundation for all database operations.
  • Using find():The find() method retrieves multiple documents based on specified filters and options.Filters like $filter = ['status' => 'active']; refine the selection.Options like 'projection' and 'sort' customize the fields retrieved and the order of the results.
  • The find() method retrieves multiple documents based on specified filters and options.
  • Filters like $filter = ['status' => 'active']; refine the selection.
  • Options like 'projection' and 'sort' customize the fields retrieved and the order of the results.
  • Working with findOne():For scenarios where you only need one document, findOne() is the go-to method.This simplifies the process as it does not require a loop to process results.
  • For scenarios where you only need one document, findOne() is the go-to method.
  • This simplifies the process as it does not require a loop to process results.
  • Comparison Operators:MongoDB supports advanced queries with operators such as $gt$lt, and $in.These operators enable more flexible filtering, such as retrieving users over 18 or filtering by multiple statuses.
  • MongoDB supports advanced queries with operators such as $gt$lt, and $in.
  • These operators enable more flexible filtering, such as retrieving users over 18 or filtering by multiple statuses.
  • Limiting and Skipping Results:Using 'limit' and 'skip', you can control how many documents are retrieved and where the retrieval starts.This is especially useful for implementing pagination in your applications.
  • Using 'limit' and 'skip', you can control how many documents are retrieved and where the retrieval starts.
  • This is especially useful for implementing pagination in your applications.
  • Counting Documents:The countDocuments() method provides the total number of documents matching a query, helping you understand the scope of your data.
  • The countDocuments() method provides the total number of documents matching a query, helping you understand the scope of your data.

In this tutorial, you learned how to retrieve documents from a MongoDB collection using PHP, with examples and detailed explanations for each method. 

Similar Reads

PHP array_intersect_ukey Function: How it Works with Examples

The array_intersect_ukey is used to compare arrays by keys with a custom function in PHP. It returns matches by keys…

PHP MySQL Create Database: MySQLi & PDO Examples

If you are working with PHP and MySQL, one of the first tasks you may need is to create a…

Traits in PHP: What They Are & Examples

PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…

How to Select Data Using PHP and MySQL?

In this article, You will understand everything you need to know about how to use PHP to select data from…

PHP is_readable: Check File Accessibility

The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

Concatenating Strings in PHP: Tips and Examples

In PHP, string operators, such as the concatenation operator (.) and its assignment variant (.=), are employed for manipulating and…

PHP mb_strtolower: How to Handle Multibyte Strings Properly

The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…

PHP array_any: How it Works with Arrays with Examples

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP strlen Function: How It Works with Strings

Developers needed a way to check the length of a string, so the strlen function was introduced to handle this…

Previous Article

Learn How to Insert Documents in MongoDB Using PHP

Next Article

How to Update Documents in MongoDB Using PHP

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.