Database Reference
In-Depth Information
// Specify the upsert options
$options = array("upsert" => true);
// Perform the update
$collection->update($criteria,$update,$options);
Next, let's look at an example where an upsert performs an insert as the document does not exist yet. Here you'll
find that the $setOnInsert criteria given will be successfully applied:
// 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("Family Name" => "Wallace");
// Specify the information to be set on upsert-inserts only
$update = array('$setOnInsert' => array("Country" => "Unknown"));
// Specify the upsert options
$options = array("upsert" => true);
// Perform the update
$collection->update($criteria,$update,$options);
This piece of code will search for any document where the Family Name -field (remember we renamed it
previously) is set to "Wallace" . If it's not found, an upsert will be done, as a result of which the Country field will be set
to "Unknown" , creating the following empty-looking document:
{
"_id" : ObjectId("1"),
"Country" : "Unknown",
"Last Name" : "Wallace"
}
Appending a Value to a Specified Field with $push
PHP's $push operator lets you append a value to a specified field. If the field is an existing array, the data will be
added; if the field does not exist, it will be created. If the field exists, but it is not an array, then an error condition will
be raised. The following example shows how to use $push to add some data into an existing array:
// 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("Family Name" => "Wood");
// Specify the information to be added
$update = array('$push' => array("E-Mail" => "vw@mongo.db"));
// Perform the update
$collection->update($criteria,$update);
 
Search WWH ::




Custom Search