So I am very new to MongoDB and PHP and I am trying to make a connection to the database and perform an insert query on it. I have managed to make it work, but know I do not really understand my own code.
My code:
<?php
// PHP version 7.4 used here
try {
require 'mongophp/vendor/autoload.php';
//$mongo = new MongoDB\Driver\Manager('mongodb://localhost:27017');
echo "Connection to database successfully\n";
$collection = (new MongoDB\Client)->shinto->users;
$insertOneResult = $collection->insertOne([
"name" => "testuser",
"password" => "1234",
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
echo "so far so good";
}
catch (Throwable $e) {
// catch throwables when the connection is not a success
echo "Captured Throwable for connection : " . $e->getMessage() . PHP_EOL;
print("\ndoes not work\n");
}
?>
The thing that I do not understand is how the code knows where my database is since I do not have to use the connection string.
My guess is that the mongophp/vendor/autoload.php takes care of this part, but I have looked through those files and can't seem to find the answer to my question in there as well.
Can someone help me understand how my code knows where my database is without a connection string or provide me with a link that will explain this to me?
Thank you very much in advance!
My Answer:
In MongoDB, the connection to the database is typically made using the MongoClient class in PHP. Here is an example of how you can make a connection to the database in PHP:
php
// MongoDB connection string
$connectionString = "mongodb://localhost:27017";
// Connect to MongoDB
$mongoClient = new MongoClient($connectionString);
// Select the database
$database = $mongoClient->selectDB('my_database');
// Select the collection
$collection = $database->selectCollection('my_collection');
// Insert a document into the collection
$document = array(
'name' => 'John Doe',
'email' => 'john.doe@example.com'
);
$collection->insert($document);
echo 'Document inserted successfully';
// Close the connection
$mongoClient->close();
?>
In the code above, the connection to the MongoDB database is made using the MongoClient class and the connection string "mongodb://localhost:27017". The code then selects the database and collection where the insert operation will be performed. Finally, a document is inserted into the collection and the connection is closed.
Please note that the MongoClient class is deprecated as of PHP 5.5.0 and has been replaced by the MongoDB\Driver\Manager class in the MongoDB PHP driver. It is recommended to use the new MongoDB PHP driver for connecting to MongoDB databases in PHP.
Rate this post
4 of 5 based on 3183 votesComments