skip to Main Content

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


  1. $m->aws_inventories That looks like as the older/deprecated approach. Could you try to follow this tutorial?

    https://zetcode.com/db/mongodbphp/

    <?php
    
    try {
    
        $mng = new MongoDBDriverManager("mongodb://localhost:27017");
    
        $stats = new MongoDBDriverCommand(["dbstats" => 1]);
        $res = $mng->executeCommand("aws_inventories", $stats);
        
        $stats = current($res->toArray());
    
        print_r($stats);
    
    } catch (MongoDBDriverExceptionException $e) {
    
        $filename = basename(__FILE__);
        
        echo "The $filename script has experienced an error.n"; 
        echo "It failed with the following exception:n";
        
        echo "Exception:", $e->getMessage(), "n";
        echo "In file:", $e->getFile(), "n";
        echo "On line:", $e->getLine(), "n";       
    }
        
    ?>
    
    Login or Signup to reply.
  2. This example is adapted from the official doc https://www.php.net/manual/en/mongodb-driver-manager.executequery.php

    <?php
    require 'vendor/autoload.php';
    
    $manager = new MongoDBDriverManager("mongodb://localhost:27017");
    $db = 'test_database';
    $col = 'mycol';
    $namespace = $db.'.'.$col;
    
    // insert data
    $bulk = new MongoDBDriverBulkWrite;
    $bulk->insert(['x' => 1]);
    $bulk->insert(['x' => 2]);
    $bulk->insert(['x' => 3]);
    $manager->executeBulkWrite($namespace, $bulk);
    
    // query
    $query = new MongoDBDriverQuery(['x' => ['$gt' => 1]], []);
    $cursor = $manager->executeQuery($namespace, $query);
    
    foreach ($cursor as $document) {
        var_dump($document);
    }
    

    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:

    <?php
    require 'vendor/autoload.php';
    
    $client = new MongoDBClient("mongodb://localhost:27017");
    $col = $client->test_database->mycol;
    
    // insert data
    $col->insertMany([
        ['x' => 1],
        ['x' => 2],
        ['x' => 3],
    ]);
    
    // query
    $docs = $col->find(['x' => ['$gt' => 1]]);
    foreach ($docs as $document) {
        var_dump($document);
    }
    
    Login or Signup to reply.
  3. First, you’re trying to access a property which doesn’t exists in MongoDBDriverManager class object.

    Second, $db = $m->aws_inventories; works with MongoDBClient 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:

    try {
        $manager = new MongoDBDriverManager('mongodb://localhost:27017');
        $command = new MongoDBDriverCommand(["listCollections" => 1]);
        
        $cursor = $manager->executeCommand("aws_inventories", $command);
        
        // list of all collections in aws_inventories
        $collections = $cursor->toArray();
        
        var_dump($collections);
    } catch (MongoDBDriverExceptionException $e) {
    }
    

    Get all documents from a collection:

    try {
        $manager = new MongoDBDriverManager('mongodb://localhost:27017');
        
        // setting options and filter
        $filter  = [];
        $options = [];
        
        /*
        // or to find specific documents based on a condition and limit records
        $filter  = [
            'service' => 'ec2',
            'instance' => 'co',
            'type' => 'c5',
            'vCPU' => [
                '$gt' => 2
            ]
        ];
        
        $options = [
            'limit' => 10,
            'maxTimeMS' => 1000,    // to limit the execution time of a query
            'sort' => [
                'vCPU' => -1
            ]
        ];
        */
        
        // constructing the query
        $query = new MongoDBDriverQuery($filter, $options);
        
        $cursor = $manager->executeQuery('aws_inventories.test', $query);
        
        foreach ($cursor as $document) {
            var_dump($document);
        }
    } catch (MongoDBDriverExceptionException $e) {
    }
    

    To perform distinct query:

    try {
        $manager = new MongoDBDriverManager('mongodb://localhost:27017');
        
        $query = [
            'size' => '2xlarge'
        ];
        $command = new MongoDBDriverCommand([
            'distinct' => 'test',   // Collection name
            'key' => 'instance',    // field for which we want to get distinct values
            'query' => $query       // criteria to filter documents
        ]);
            
        $cursor = $manager->executeCommand("aws_inventories", $command);
        
        // to get distinct values as array
        $instances = current($cursor->toArray())->values;
        
        var_dump($instances);
    } catch (MongoDBDriverExceptionException $e) {
    }
    

    To insert single/multiple document/s:

    try {
        $manager = new MongoDBDriverManager('mongodb://localhost:27017');
        $bulk = new MongoDBDriverBulkWrite;
    
        $bulk->insert([
            'service' => 'ec2',
            'instance' => 'co',
            'type' => 'c5',
            'size' => 'large',
            'model' => 'c5.large',
            'vCPU' => 2,
            'memory' => 4,
            'storage' => 'ebs-only',
            'network_bandwidth' => 10,
            'ebs_bandwidth' => 4750  
        ]);
        
        $bulk->insert([
            'service' => 'ec2',
            'instance' => 'gp',
            'type' => 't3',
            'size' => 'nano',
            'model' => 't3.nano',
            'vCPU' => 2,
            'memory' => 0.5,
            'storage' => 'ebs-only',
            'network_bandwidth' => 5 
        ]);
        
        $result = $manager->executeBulkWrite('aws_inventories.test', $bulk);
        
    } catch (MongoDBDriverExceptionException $e) {
    }
    

    To update existing document/s: (Taken from executeUpdate example)

    try {
        $manager = new MongoDBDriverManager('mongodb://localhost:27017');
        $criteria = [
            'service' => 'ec2',
            'type' => 'c5'
        ];
        
        $document = [
            '$set' => [
                'features' => [
                    'Powered by the AWS Nitro System, a combination of dedicated hardware and lightweight hypervisor'
                ]           
            ]       
        ];
    
        $updateOptions = array(
            'multi' => true,    // false - to update only first matching document, true - update all matching documents
            'upsert' => 0
        );
        
        $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 100);
    
        $result = $manager->executeUpdate('aws_inventories.test', $criteria, $document, $updateOptions, $writeConcern);
        
        printf("Updated %d document(s)n", $result->getModifiedCount());
        printf("Matched %d document(s)n", $result->getMatchedCount());
        printf("Upserted documents: %dn", $result->getUpsertedCount());
        foreach ($result->getUpsertedIds() as $index => $id) {
            printf("upsertedId[%d]: ", $index);
            var_dump($id);
        }
        
        /* If the WriteConcern could not be fulfilled */
        if ($writeConcernError = $result->getWriteConcernError()) {
            printf("%s (%d): %sn", $error->getMessage(), $error->getCode(), var_export($error->getInfo(), true));
        }
        
        /* If the write could not happen at all */
        foreach ($result->getWriteErrors() as $writeError) {
            printf("%s (%d)n", $error->getMessage(), $error->getCode());
        }
    } catch (MongoDBDriverExceptionException $e) {
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search