Description
refer:
http://docs.mongodb.org/manual/core/update/#update-operations-with-the-upsert-flag
http://php.net/manual/en/mongocollection.update.php
Example #2 MongoCollection::update() upsert examples
Upserts can simplify code, as a single line can create the document if it does not exist (based on $criteria), or update an existing document if it matches.
In the following example, $new_object contains an atomic modifier. Since the collection is empty and upsert must insert a new document, it will apply those operations to the $criteria parameter in order to create the document.
drop(); $c->update( ``` array("uri" => "/summer_pics"), array('$inc' => array("page hits" => 1)), array("upsert" => true) ``` ); var_dump($c->findOne()); ?>The above example will output something similar to:
array(3) {
["_id"]=>
object(MongoId)#9 (0) {
}
["uri"]=>
string(12) "/summer_pics"
["page hits"]=>
int(1)
}
If $new_object does not contain atomic modifiers (i.e. $ operators), upsert will use $new_object as-is for the new document. This matches the behavior of a normal update, where not using atomic modifiers causes the document to be overwritten.
The above example will output something similar to:
array(3) {
["_id"]=>
object(MongoId)#10 (0) {
}
["username"]=>
string(6) "joe312"
["createdAt"]=>
object(MongoDate)#4 (0) {
}
}