Updating documents

As with queries, when performing updates, PHPLIB closely mirrors the JavaScript equivalent. Thus, the following methods are available:

  • MongoDB\Collection::replaceOne()
  • MongoDB\Collection::updateOne()
  • MongoDB\Collection::updateMany()
  • MongoDB\Collection::findOneAndReplace()
  • MongoDB\Collection::findOneAndUpdate()

In this example, we will use the same filter as we did previously (the ObjectID for the customer Spencer Sanford) and update the balance:

 // here is the JavaScript query we wish to emulate: // db.customers.updateOne( //     {_id:ObjectId("5b47108b533b8406ac227798")}, //     {$set:{balance:99.99}} // );  $filter = ['_id' => new ObjectId('5b47108b533b8406ac227798')]; try {     $document = $collection->findOne($filter); printf("Name: ...

Get MongoDB 4 Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.