Chapter 3. Advanced MongoDB

Now that you have the basics down, you should feel quite ready to build most applications, or at least the majority of functionality in any application. This section will take you into deeper functionality, enabling you to do even more with MongoDB. We will cover regular expressions, aggregation, MapReduce, replication, and sharding.

Regular Expressions

In addition to all of the logical operators provided, MongoDB also provides a full regular expression (regex) engine. Regular expressions are run against strings and between the two, there really isn't any query you can’t create (within a single collection; across multiple collections, you’ve got MapReduce and client logic at your disposal).

To best illustrate the usage of regular expressions and how they pertain to indexes, we will use a data set of colors:

$db->colors->save(array('color' => 'red')); $db->colors->save(array('color' => 'blue')); $db->colors->save(array('color' => 'green')); $db->colors->save(array('color' => 'purple')); $db->colors->save(array('color' => 'orange')); $db->colors->save(array('color' => 'turquoise')); $db->colors->save(array('color' => 'black')); $db->colors->save(array('color' => 'brown')); $db->colors->save(array('color' => 'teal')); $db->colors->save(array('color' => 'silver')); $db->colors->save(array('color' => 'tan')); $db->colors->save(array('color' => 'navy')); $db->colors->save(array('color' => 'yellow')); $db->colors->save(array('color' => 'indigo')); $db->colors->ensureIndex('color'); ...

Get MongoDB and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.