1

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.

2
  • that does not construct an array but more like a string of comma separated field names, most likely due to some quirk in the driver you are getting mysteriously only _id back using it Commented Jul 2, 2013 at 22:07
  • I guess I got confused by the print_r result showing it as an array. At least now I know where to look. Thanks. Commented Jul 2, 2013 at 22:17

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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