Querying

Distributing queries to secondaries

All queries (reads and writes) are only sent to the primary member of a
replica set by default. This is however easily configurable by using the
Read Preferences which allow
you to set some generic read preferences (such as allowing secondary reads
of the nearest server), and also provide ways to specifically target a
server in a specific country, datacenter, or even hardware, by the use of
replica set tag sets.

In this example, the the query will be executed against a secondary. The
collection inherits MongoClient::RP_SECONDARY_PREFERRED
from the database and the cursor inherits it from the collection.

How secondaries are chosen

Each instance of MongoClient chooses its own
secondary using the available secondary with the lowest ping time. So, if we
had a PHP client in Europe and one in Australia and we had one secondary in
each of these data centers, we could do:

If no secondary is readable, the driver will send reads to the
primary as we specified
MongoClient::RP_SECONDARY_PREFERRED which will
fallback to execute a query on a primary if no secondaries are available.
A server is considered readable if its state is 2 (SECONDARY) and its
health is 1. You can check this with
MongoClient::getHosts() and
MongoClient::getConnections().

Random notes

Writes are always sent to the primary—and by default all reads are sent
to the primary too.

Querying by _id

Every object inserted is automatically assigned a unique
_id field, which is often a useful field to use in
queries. This works similarly to "get last insert ID" functionality, except
that the _id is chosen by the client.

Suppose that we wish to find the document we just inserted. Inserting adds
an _id field to the document, so we can query by that:

Unless the user has specified otherwise, the _id field is a
MongoId. The most common mistake is attempting to use
a string to match a MongoId. Keep in mind that these
are two different datatypes, and will not match each other in the same way
that the string "array()" is not the same as an empty array. For example:

Arrays

Arrays are special in a couple ways. First, there are two types that
MongoDB uses: "normal" arrays and associative arrays. Associative arrays can
have any mix of key types and values. "Normal" arrays are defined as arrays
with ascending numeric indexes starting at 0 and increasing by one for each
element. These are, typically, just your usual PHP array.

For instance, if you want to save a list of awards in a document, you could
say: