Home » Php » php – Call to undefined method MongoDB\Collection::insert() in [PATH] on line 20

php – Call to undefined method MongoDB\Collection::insert() in [PATH] on line 20

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to insert a json array into my MongoDB, that sounds a simple task. I use MongoDB 3.2, PHP 5.5 and XamppServer 32 bit. I have already installed PHP Driver for MongoDB and Composer. So I tried to run the code below:

require "vendor/autoload.php";

// create connection
$m = new MongoDB\Client();
// select a database
$db = $m->test;
// select a collection
$collection = $db->foo;

//insert to Database
$document = array( "title" => "Mongo Sample", "number" => 2 );
$collection->insert($document);

But on running, I got this error:

**Fatal error:** Call to undefined method MongoDB\Collection::insert() in C:\xampp\...\test.php on line 13

I can’t figure out how to fix the problem.

How to&Answers:

Instead of method MongoDB\Collection::insert() using insertOne() or insertMany() would work!

Answer:

    You can set you code as below mentioned...
    $client = new MongoClient("mongodb://MONGOUSERNAME:[email protected]:27017/DBNAMEB");
// it authenticate mongo client with username password, host and database name 
// if username, pwd not available leave it blank default db here is admin 
    if($client)
    {
    echo "Hello Mongo"."</br>";
    }
// If all credential is correct it will connect else display error
    else
    {
    echo "Mongodb client error";
    }
    $db = $client->myqsoft;
// Here we can change working database.
    $coll = $db->employee;
// Now we select aur current working table or collection..
    $data = array("Name" => "Mayank Agarwal", "Dept" => "UI Developer", "City" => "Meerut", "Mobile" => "Meerut" );

// Variable data have value of different variables you can choose as yours   

$coll->insert($data);

// It insert data in selected column.. 

// It will work.. keep coding..