Database Reference
In-Depth Information
Adding Multiple Values to a Key with $push and $each
The $push operator also lets you append multiple values to a key. For this, the $each modifier needs to be added. The
values, presented in an array, will be added in case they do not exist yet within the given field. As the $push operator
is being used, the same general rules apply: if the field exists, and it is an array, then the data will be added; if it does
not exist, then it will be created; if it exists, but it isn't an array, then an error condition will be raised. The following
example illustrates how to use the $each modifier:
// 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" => array(
'$each' => array(
"vicwo@mongo.db",
" vicwo@example.com "
)
)
)
);
// Perform the update
$collection->update($criteria,$update);
Adding Data to an Array with $addToSet
The $addToSet operator is similar to the $push operator, with one important difference: $addToSet ensures that data is
added to an array only if the data is not in there. The $addToSet operator takes one array as a parameter:
// 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 (successful because it doesn't exist yet)
$update = array('$addToSet' => array("E-Mail" => " vic@example.com " ));
// Perform the update
$collection->update($criteria,$update);
Similarly, you can add a number of items that don't exist yet by combining the $addToSet operator with the $each
operator:
// Connect to the database
$c = new MongoClient();
// Select the collection 'people' from the database 'contacts'
$collection = $c->contacts->people;
 
Search WWH ::




Custom Search