php mongodb : Call to undefined method MongoDB::insert() in db.php

10,521

Each DB contains one or many collections. You are trying to insert into the DB, instead of the collection.

I've not used that extension, but that method doesn't exist in the MongoDB class according to the documentation. Instead, it is MongoCollection::insert. You get at a collection by:

// $collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar; 
$collection->insert(array('x' => 1));

(The commented line is equivalent to the line below it.)

I'm guessing that you are doing something like:

$collection = $mongo->foo;
$collection->insert(array('x' => 1));

(Edit: I didn't see your code snippet the first time. That is precisely what you are doing.)

I suggest that you read the tutorial for more information.

Share:
10,521
JSNewbie
Author by

JSNewbie

Updated on July 25, 2022

Comments

  • JSNewbie
    JSNewbie almost 2 years

    I'm running this code:

        $db = new Mongo("mongodb://user:[email protected]:27081/dbname");
        $collection = $db->foobar;
    
        $collection->insert($content);
    

    I'm trying to test mongohq by just creating a random collection.

    I'm getting this error:

    Fatal error:  Call to undefined method MongoDB::insert() in /ajax/db.php on line 24
    

    I have the client installed as far as I know:

    alt text

    I'm also running php 5.2.6

    What's the problem? Thanks.

  • JSNewbie
    JSNewbie over 13 years
    Isn't dbname at the end of the new Mongo the db? So I wouldn't have to select it twice?
  • Matthew
    Matthew over 13 years
    You don't insert into a db. You insert into a collection. The $mongo instance is just a connection to a mongo server. The first property is the name of the database. The second is the name of the collection.