Deleting documents

To delete documents from the collection using PHPLIB, we can use either of the following:

  • MongoDB\Collection::deleteOne()
  • MongoDB\Collection::deleteMany()

In this example, we first perform a find() to confirm the filter. After confirmation we issue a deleteMany() command to will remove all customers whose balance is less than or equal to zero, but whose name is not admin. Here is the JavaScript command we wish emulate:

db.customers.deleteMany({balance:{$lte:0},name:{$ne:"admin"}},{name:1});

The initial setup is exactly like the previous example (we create an Application\Client instance). The setup for the filter which emulates the preceding JavaScript command looks like this:

$filter = [     'balance' => ['$lte' => 0], '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.