I’m trying to use MongoDB on my local machine using the advice in this stack overflow. I’m using XAMPP on Windows 10, php version 8.01, and MongoDB extension 1.9.0.
It’s a very basic script that connects to MongoDB and tries to use one of the databases.
But I am still getting this warning:
Connection to database successfully
Warning: Undefined property: MongoDBDriverManager::$aws_inventories in C:xampphtdocsmongo_connect.php on line 8
This is my code:
<?php
require 'C:xampphtdocsvendorautoload.php'; // include Composer's autoloader
$DB_CONNECTION_STRING="mongodb://localhost:27017";
// connect to mongodb
$m = new MongoDBDriverManager( $DB_CONNECTION_STRING );
echo "Connection to database successfully";
// select a database
$db = $m->aws_inventories;
?>
How can I get rid of the warning and connect to the DB correctly?
3
Answers
$m->aws_inventories
That looks like as the older/deprecated approach. Could you try to follow this tutorial?https://zetcode.com/db/mongodbphp/
This example is adapted from the official doc https://www.php.net/manual/en/mongodb-driver-manager.executequery.php
As the document suggests, MongoDBDriverManager is a generic abstraction to manage any type of MongoDB connection (standalone server, replica set, or sharded cluster) so the methods will look a bit too complicated for simple CRUD on standalone server.
If you just want to connect to a standalone server, you may want to check MongoDBClient. Here is the code that do exactly the same thing:
First, you’re trying to access a property which doesn’t exists in
MongoDBDriverManager
class object.Second,
$db = $m->aws_inventories;
works withMongoDBClient
library.Here are few example to get collections list or find all/specific document/s or insert/bulk insert, update a document or to perform a distinct query
Get all collections of aws_inventories:
Get all documents from a collection:
To perform distinct query:
To insert single/multiple document/s:
To update existing document/s: (Taken from executeUpdate example)