Reading documents

You will note that PHPLIB closely mirrors the JavaScript API. In order to read (query) the database, these two methods are the ones that are used the most:

  • MongoDB\Collection::find()
  • MongoDB\Collection::findOne()

In addition, PHPLIB includes methods to find and then replace, update, or delete:

  • MongoDB\Collection::findOneAndDelete()
  • MongoDB\Collection::findOneAndReplace()
  • MongoDB\Collection::findOneAndUpdate()

In this example, we wish to reproduce this JavaScript command using PHPLIB:

db.customers.find(     {country:/UK/,balance:{$lt:100}},     {_id:0,name:1,email:1,phone:1,balance:1} ).sort({balance:1});

First, we initialize the environment:

require __DIR__ . '/vendor/autoload.php'; use MongoDB\BSON\Regex; use Application\ {Client, ...

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.