H. Ati
H. Ati

Reputation: 281

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

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.

Upvotes: 8

Views: 8844

Answers (2)

Sonpal singh Sengar
Sonpal singh Sengar

Reputation: 247

    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..

Upvotes: 0

H. Ati
H. Ati

Reputation: 281

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

Upvotes: 16

Related Questions