Reputation:
I have a PHP script that gathers data from MongoDB and prints it. Some options are gathered from $_POST
supergoblal. Everything works fine but I can't limit the fields to return using an array.
$results = $db->$table->find($param); //This line works and returns all fields
$results = $db->$table->find($param, array('Descripción','Ocurrencias relacionadas'));//This line works and limit the returned fields to the ones specified.
The following code constructs an array to use as a field limiter parameter:
$fields=implode(',', $_POST[field]);
$fd = array($fields);
print_r($fd)
shows:
Array ( [0] => 'Descripción','Ocurrencias relacionadas' )
$results = $db->$table->find($param,$fd);` //This line works and returns all documents but only _id field.
Any ideas? It's driving me mad! Thanks in advance.
Upvotes: 1
Views: 1585
Reputation: 36794
You are running your query in the wrong way. First of all, you don't show what $param
is, but let's assume it is a query like:
$param = array( 'field1' => 'foo' );
Then as second argument you pass in an array with two values, but that is not what this method wants. The second argument is an array of fields to return, in the following format:
array( 'Descripción' => 1, 'Ocurrencias relacionadas' => 1 );
You pass in the following:
array( 0 => 'Descripción', 1 => 'Ocurrencias relacionadas');
Which means to only show the fields with the names 0 and 1 (which likely don't exist). The _id
field is always return so that's why it shows up.
What you need to do, is to pass in the field names as keys in the second argument to find()
:
$fields=implode(',', $_POST[field]);
$fd = array($fields);
$fd = array_flip($fd); // << important to make the values keys and they keys values: php.net/array_flip
$results = $db->$table->find($param, $fd);
Upvotes: 1