Database Reference
In-Depth Information
[Postal Code] => SA9 6XS
[Country] => UK
)
[E-Mail] => Array (
[0] => vw@example.com
[1] => vw@office.com
)
[Phone] => 078-8727-8049
[Age] => 28
)
This is a lot of work just to change one value—not exactly what you'd want to be doing to make a living. However,
this is precisely what you would have to do if you didn't use PHP's modifier operators. Now let's look at how you can
use these operators in PHP to make life easier and consume less time.
If you don't specify any of the conditional operators when applying the change, the data in the matching
document(s) will be replaced by the information in the array. generally, it's best to use $set if you want to change only one field.
Warning
Saving Time with Update Operators
The update operations are going to save you loads of typing. As you'll probably agree, the preceding example is
just not feasible to work with. Fortunately, the PHP driver includes about half a dozen update operators for quickly
modifying your data, without going through the trouble of writing it out fully. The purpose of each operator will be
briefly summarized again, although you are probably familiar with most of them at this point (you can find more
information about all the update operators discussed in this section in Chapter 4). However, the way you use them in
PHP differs significantly, as do the options associated with them. We'll look at examples for each of these operators,
not least so you can familiarize you with their syntax in PHP.
none of the update operators that follow will include php code to review the changes made; rather, the ex-
amples that follow only apply the changes. It's suggested that you fire up the MongodB shell alongside of the php code,
so you can perform searches and confirm that the desired changes have applied. alternatively, you can write additional
php code to perform these checks.
Note
Increasing the Value of a Specific Key with $inc
The $inc operator allows you to increase the value of a specific key by n , assuming that the key exists. If the key does not
exist, it will be created instead. The following example increases the age of each person younger than 40 by three years:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Search for anyone that's younger than 40
$criteria = array("Age" => array('$lt' => 40));
// Use $inc to increase their age by 3 years
$update = array('$inc' => array('Age' => 3));
 
 
Search WWH ::




Custom Search