Database Reference
In-Depth Information
// Options
$options = array("upsert" => true);
// Perform the update
$collection->update($criteria,$update,$options);
Changing the Value of a Key with $set
The $set operator lets you change the value of a key while ignoring any other fields. As noted previously, this would
have been a much better choice for updating Victoria's first name to "Vicky" in the earlier example. The following
example shows how to use the $set operator to change the contact's name to "Vicky" :
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Specify the search criteria
$criteria = array("Last Name" => "Wood");
// Specify the information to be changed
$update = array('$set' => array("First Name" => "Vicky"));
// Options
$options = array("upsert" => true);
// Perform the update
$collection->update($criteria,$update,$options);
You can also use $set to add a field for every occurrence found matching your query:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
// Specify the search criteria using regular expressions
$criteria = array("E-Mail" => new MongoRegex(" /@office.com/i "));
// Add "Category => Work" into every occurrence found
$update = array('$set' => array('Category' => 'Work'));
// Options
$options = array('upsert' => true, 'multi' => true);
// Perform the upsert via save()
$collection->update($criteria,$update,$options);
Deleting a Field with $unset
The $unset operator works similarly to the $set operator. The difference is that $unset lets you delete a given field
from a document. For instance, the following example removes the Phone field and its associated data from the
contact information for Victoria Wood:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
 
Search WWH ::




Custom Search