Docs Menu
Docs Home
/
PHP Library Manual
/ /

Retrieve Data

In this guide, you can learn how to use the MongoDB PHP Library to retrieve data from a MongoDB collection by using read operations. You can call the MongoDB\Collection::find() or MongoDB\Collection::findOne() method on a collection to retrieve documents that match a set of criteria.

The examples in this guide use the companies collection in the sample_training database from the Atlas sample datasets. To access this collection from your PHP application, instantiate a MongoDB\Client that connects to an Atlas cluster and assign the following value to your $collection variable:

$collection = $client->sample_training->companies;

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

The MongoDB PHP Library includes two methods for retrieving documents from a collection: MongoDB\Collection::findOne() and MongoDB\Collection::find(). These methods take a query filter and return one or more matching documents. A query filter specifies the search criteria that the driver uses to retrieve documents in your query.

Tip

To learn more about query filters, see the Specify a Query guide.

To find a single document in a collection, call the MongoDB\Collection::findOne() method and pass a query filter that specifies the criteria of the document you want to find.

The findOne() method returns an array, object, or null value. If the query filter matches a document, the method returns an array|object instance containing the document. The return type depends on the value of the typeMap option. If the query filter does not match any documents, the method returns null.

Tip

To learn more about findOne() options, such as typeMap, see the Modify Find Behavior section of this guide.

If the query filter matches more than one document, the findOne() method returns the first matching document from the retrieved results.

The following example uses the findOne() method to find the first document in which the name field has the value 'LinkedIn':

$document = $collection->findOne(['name' => 'LinkedIn']);
echo json_encode($document), PHP_EOL;
{"_id":{"$oid":"..."},"name":"LinkedIn","permalink":"linkedin","crunchbase_url":
"http:\/\/www.crunchbase.com\/company\/linkedin","homepage_url":"http:\/\/linkedin.com",
... }

Tip

Sort Order

The findOne() method returns the first document in natural order on disk if no sort criteria is specified.

To find multiple documents in a collection, pass a query filter to the MongoDB\Collection::find() method that specifies the criteria of the documents you want to retrieve.

The following example uses the find() method to find all documents in which the founded_year field has the value 1970:

$results = $collection->find(['founded_year' => 1970]);

The find() method returns an instance of MongoDB\Driver\Cursor, which you can iterate over to see the matching documents. A cursor is a mechanism that allows an application to iterate over database results while holding only a subset of them in memory at a given time. Cursors are useful when your find() method returns a large amount of documents.

You can iterate over the documents in a cursor by using a foreach loop, as shown in the following example:

foreach ($results as $doc) {
echo json_encode($doc), PHP_EOL;
}
{"_id":{"$oid":"..."},"name":"Mitsubishi Motors","permalink":"mitsubishi-motors",
"crunchbase_url":"http:\/\/www.crunchbase.com\/company\/mitsubishi-motors",
... }
{"_id":{"$oid":"..."},"name":"Western Digital","permalink":"western-digital",
"crunchbase_url":"http:\/\/www.crunchbase.com\/company\/western-digital",
... }
{"_id":{"$oid":"..."},"name":"Celarayn","permalink":"celarayn","crunchbase_url":
"http:\/\/www.crunchbase.com\/company\/celarayn",
... }

Note

Find All Documents

To find all documents in a collection, pass an empty filter to the find() method:

$cursor = $collection->find([]);

You can modify the behavior of the MongoDB\Collection::find() and MongoDB\Collection::findOne() methods by passing an array that specifies option values as a parameter. The following table describes some options you can set in the array:

Option
Description

batchSize

The maximum number of documents within each batch returned in a query result. By default, the find command has an initial batch size of 101 documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. If you set batchSize to a limit that results in batches larger than 16 MiB, this option has no effect.
Type: integer

collation

The collation to use for the operation. The default value is the collation specified for the collection. To learn more, see the Collation section of this page.
Type: array|object

comment

The comment to attach to the operation.
Type: any BSON type

cursorType

The type of cursor to use for the operation. The default value is MongoDB\Operation\Find::NON_TAILABLE.
Type: MongoDB\Operation\Find

limit

The maximum number of documents the operation can return.
Type: integer

skip

The number of documents to skip before returning results.
Type: integer

sort

The order in which the operation returns matching documents.
Type: array|object

typeMap

The type map to apply to cursors, which determines how BSON documents are converted to PHP values. The default value is the collection's type map.
Type: array

The following example uses the find() method to find all documents in which the number_of_employees field has the value 1000. The example uses the limit option to return a maximum of 5 results:

$results = $collection->find(
['number_of_employees' => 1000],
['limit' => 5]
);
foreach ($results as $doc) {
echo json_encode($doc), PHP_EOL;
}

For a full list of options, see the API documentation for the findOne() and find() parameters.

To specify a collation for your operation, pass an $options array parameter that sets the collation option to the operation method. Assign the collation option to an array that configures the collation rules.

The following table describes the fields you can set to configure the collation:

Field
Description

locale

(Required) Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server manual.

Data Type: string

caseLevel

(Optional) Specifies whether to include case comparison.

When set to true, the comparison behavior depends on the value of the strength field:

- If strength is 1, the PHP library compares base
characters and case.

- If strength is 2, the PHP library compares base
characters, diacritics, other secondary differences, and case.

- If strength is any other value, this field is ignored.

When set to false, the PHP library doesn't include case comparison at strength level 1 or 2.

Data Type: bool
Default: false

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: string
Default: "off"

strength


Data Type: int
Default: 3

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If set to true, the PHP library compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the library uses the strings' numeric values and treats "10" as greater than "2".

If set to false, the PHP library compares numeric strings as strings. For example, when comparing the strings "10" and "2", the library compares one character at a time and treats "10" as less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: bool
Default: false

alternate

(Optional) Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.

Data Type: string
Default: "non-ignorable"

maxVariable

(Optional) Specifies which characters the library considers ignorable when the alternate field is set to "shifted".

Data Type: string
Default: "punct"

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: bool
Default: false

To learn more about collation and the possible values for each field, see the Collation entry in the MongoDB Server manual.

To learn more about query filters, see the Specify a Query guide.

To learn more about any of the methods discussed in this guide, see the following API documentation:

Back

Query Documents

On this page