Database Reference
In-Depth Information
Removing Each Occurrence of a Value with $pull
You can use PHP's
$pull
operator to remove each occurrence of a given value from an array. For example, this is
handy if you've accidentally added duplicates to an array when using
$push
or
$pushAll
. The following example
removes any duplicate occurrence of an e-mail address:
// 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");
// Pull out each occurrence of the e-mail address "
vicky@example.com
"
$update = array('$pull' => array("E-Mail" => "
vicky@example.com
"
));
// Perform the update
$collection->update($criteria,$update);
Removing Each Occurrence of Multiple Elements
Similarly, you can use the
$pullAll
operator to remove each occurrence of multiple elements from your documents,
as shown in the following example:
// 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");
// Pull out each occurrence of the e-mail addresses below
$update = array(
'$pullAll' => array(
"E-Mail" => array("vw@mongo.db","
vw@office.com
"
)
)
);
// Perform the update
$collection->update($criteria,$update);
Upserting Data with save()
Like the
insert()
function, the
save()
function allows you to insert data into your collection. The only difference
is that you can also use
save()
to update a field that already holds data. As you might recall, this is called an
upsert
.
The way you execute the
save()
function shouldn't come as a surprise at this point. Like the
save()
function in the
MongoDB shell, PHP's
save()
takes two parameters: an array that contains the information you wish to save, and any
options for the save. The following options can be used:
fsync
: If set to
true
, this Boolean option causes the data to be synced to disk before returning a
success. If this option is set to
true
, then it's implied that
w
is set to
0
, even if it's set otherwise.
•
w
: If set to 0, the save operation will not be acknowledged. When working with replica sets, w
can also be set to
n
, ensuring that the primary server acknowledges the save operation when
successfully replicated to
n
nodes. Can also be set to
'majority'
—a reserved string—to
•