lowcrawler
lowcrawler

Reputation: 7549

How to get entire MongoDB collection with PHP

Using the following code, I can grab a node from a collection:

<?php

$user = "xxxx";
$pwd = 'xxxx';

if (isset($_POST['needleID'])) {
    $needleID = $_POST['needleID'];
} else {
    echo "needle ID not set";
}

//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}@localhost:27017");

// Query Class
$filter = ['id'=> $needleID];
$query = new MongoDB\Driver\Query($filter);

// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('DBNAME.DBCOLLECTION', $query);

// Convert rows to Array and send result back to javascript as json
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);

?>

However, what I'm really looking to do is get everything from the DBCOLLECTION.

I'm kind of at a loss on how to do this. A few searches either go over my head or are for older versions of the PHP driver, such as this one fetch all data from mongodb collection

Upvotes: 1

Views: 2608

Answers (2)

zoonman
zoonman

Reputation: 1163

It is better to use mongoexport for exporting collections. On large collections your code will be slow and will timeout. Consider using pagination for results.

Upvotes: 0

B. Fleming
B. Fleming

Reputation: 7220

If you query on a specific ID, then you will only receive the document with that ID as its value. If you want to retrieve all document in a collection, leave the filter empty, i.e. with $filter = [];.

Upvotes: 3

Related Questions