composer require mongodb/mongodb
vendor directory containing the required files.connect.php. Add the following code:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
?>
Client class. We then create a new instance of the Client class, specifying the MongoDB server's connection URL. Adjust the URL if your MongoDB server is running on a different host or port.insertOne() method. Here's an example:<?php
$collection = $client->test->users;
$newUser = [
'name' => 'John',
'email' => '[email protected]',
'age' => 25
];
$insertResult = $collection->insertOne($newUser);
echo "Inserted document ID: " . $insertResult->getInsertedId();
?>
users collection within the test database. We create a new document as an associative array and then use the insertOne() method to insert it into the collection. Finally, we retrieve and display the ID of the inserted document using the getInsertedId() method.find() method. Here's an example:<?php
$collection = $client->test->users;
$documents = $collection->find();
foreach ($documents as $document) {
echo $document['name'] . ': ' . $document['email'] . "\n";
}
?>
users collection. We iterate over the result using a foreach loop and access specific fields, such as the name and email, to display their values.updateOne() method. Here's an example:<?php
$collection = $client->test->users;
$updateResult = $collection->updateOne(
['name' => 'John'],
['$set' => ['age' => 30]]
);
echo "Modified " . $updateResult->getModifiedCount() . " document(s).";
?>
age field of the document with the name 'John' using the $set operator. The updateOne() method updates the first matching document. We then retrieve the number of modified documents using the getModifiedCount() method.deleteOne() method. Here's an example:<?php
$collection = $client->test->users;
$deleteResult = $collection->deleteOne(['name' => 'John']);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
?>
deleteOne() method removes the first matching document, and we retrieve the number of deleted documents using the getDeletedCount() method.SPONSORS