The mongo shell has the db.collection.save() command, which can be used to replace an existing document.
What is the equivalent in PHP?
The mongo shell has the db.collection.save() command, which can be used to replace an existing document.
What is the equivalent in PHP?
You're looking for MongoDB\Collection::updateOne in the PHP MongoDB library.
However, you need the upsert option to set to true which would emulate the "update if exists, create if it doesn't" behaviour of db.collection.save().
Some sample code from MongoDB's PHP Library Manual (great resource):
<?php
$collection = (new MongoDB\Client)->test->users;
$collection->drop();
$updateResult = $collection->updateOne(
['name' => 'Bob'],
['$set' => ['state' => 'ny']],
['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());
$upsertedDocument = $collection->findOne([
'_id' => $updateResult->getUpsertedId(),
]);
var_dump($upsertedDocument);
Output:
Matched 0 document(s)
Modified 0 document(s)
Upserted 1 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#15 (1) {
["oid"]=>
string(24) "57509c4406d7241dad86e7c3"
}
["name"]=>
string(3) "Bob"
["state"]=>
string(2) "ny"
}
}