Skip to content
Advertisement

Specify Mongo DB and Collection name as variables in PHP

MongoDB’s PHP library allows me to connect to a collection like this (from example):

$m = new Mongo(); 
$db = $m->comedy; 
$collection = $db->cartoons;

But how do I specify the database and/or the collection name as a variable? What I want to do is something like this:

$m = new Mongo();
$dbname = "comedy"; 
$collectionname = "cartoons"; 
$db = $m[$dbname]; 
$collection = $db[$collectionname];

I can do this using the Python API, so I find it strange that I am not able to do it using PHP.

UPDATE: This is the error I am getting when I use the above method, which leads me to believe there’s no built-in way to address MongoDB collections using variable names?

Fatal error: Cannot use object of type Mongo as array

ANSWER: As per accepted answer below, this will work:

$db = $m->$dbname; 
$collection = $db->$collectionname;

Advertisement

Answer

You can still get it by a variable using -> ie $m->$dbname via http://php.net/manual/en/mongo.tutorial.php

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement