Calling the undefined method MongoDB \ Collection :: insert () on [PATH] on line 20

I want to insert a json array into my MongoDB, this sounds like a simple task. I am using MongoDB 3.2, PHP 5.5 and XamppServer 32 bit. I have already installed the 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 at startup, I got this error:

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

I cannot figure out how to fix this problem.

+4
source share
2 answers

Instead, a method MongoDB\Collection::insert()using insertOne()or insertMany()will work!

+8
source
    You can set you code as below mentioned...
    $client = new MongoClient("mongodb://MONGOUSERNAME:MONGOPASSWORD@127.0.0.1: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..
0
source

Source: https://habr.com/ru/post/1663619/


All Articles