2

I'm trying to get all the collection from a database in mongodb with PHP but I didn't find anything on internet useful.

This is what I get so far

$client = new MongoDB\client;
$database = $client->database2;
$collections = $database->listCollections();

foreach ($collections as $collection) {
    echo $collection;
}

I'm using listCollections() but doesn't work. I just need to get all data to show it.

This is my folder structure if it helps

This is the output:

Recoverable fatal error: Object of class MongoDB\Model\CollectionInfo could not be converted to string

3
  • And what is your output? What do you mean with "doesn't work"? Commented Mar 5, 2018 at 17:15
  • yes, sorry! I already edited the question. Commented Mar 5, 2018 at 17:17
  • Please read How does accepting an answer work?. Do not edit the word "solved" in to the question title. Accepting an answer is how you mark a question as successfully answered. Commented Apr 16, 2018 at 8:07

2 Answers 2

3

Finally, I could do it with getName() to get all the collections name from my database.

$colecciones = $database->listCollections();
foreach ($colecciones as $col) {
    echo $col->getName();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your result is an object and you try to convert them to a string with an echo. So use var_dump() for example to make the object visible. Then you can use the methods to get more informations from the collection.

One of the methods is getName() you can use them to get the name of the collection.

MongoDBModelCollectionInfo

5 Comments

so how you would do it? because I'm still getting an error message with getName() Fatal error: Uncaught Error: Call to undefined function getName()
Make a var_dump on the $collection then look at the structure and then you can access the methods.
yes, but I mean how could I use getName(), to know the name of every collections.
This is what I get using var_dump of one of the collections object(MongoDB\Model\CollectionInfo)#24 (5) { ["name"]=> string(10) "medidor442" ["type"]=> string(10) "collection" ["options"]=> array(0) { } ["info"]=> array(2) { ["readOnly"]=> bool(false) ["uuid"]=> object(MongoDB\BSON\Binary)#21 (2) { ["data"]=> string(16) "K�/|�Bߋ��Z��" ["type"]=> int(4) } } ["idIndex"]=> array(4) { ["v"]=> int(2) ["key"]=> array(1) { ["id"]=> int(1) } ["name"]=> string(4) "_id" ["ns"]=> string(20) "database2.medidor442" } }
Try something like this: $collection->name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.