Amar
Amar

Reputation: 895

Insert data in MongoDB using PHP

I am on php 5.6 using WAMP and want to insert a document into MongoDB using PHP. I am doing it in this way:

<?php

   require 'vendor/autoload.php';

   $con = new MongoDB\Client("mongodb://localhost:27017");
   echo "successfully";

   $db = $con->selectDatabase('DB');
   echo "Selected";

   $col = $db->selectCollection('myCol');
   $document = array( 
      "name" => "Deny", 
      "password" => "1234"
   );

   $col->insert($document);
   echo "successfully";

   ?>

But it is giving the error

Fatal error: Call to undefined method MongoDB\Collection::insert() in C:\wamp64\www...

I have read http://php.net/manual/en/mongocollection.insert.php and when I use the same insert function, it doesn't work for me.

Upvotes: 4

Views: 12281

Answers (3)

shashwat yadav
shashwat yadav

Reputation: 11

Instead of MongoDB\Client use MongoClient .

This works for me.

Upvotes: 1

Imran
Imran

Reputation: 345

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

Upvotes: 0

Kristiyan
Kristiyan

Reputation: 1663

You have to install MongoClient library: http://php.net/manual/en/mongo.installation.php

Upvotes: 0

Related Questions