1

我有一个从 MongoDB 收集数据并打印出来的 PHP 脚本。一些选项是从$_POSTsupergoblal 收集的。一切正常,但我不能限制使用数组返回的字段。

$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.

以下代码构造一个数组以用作字段限制器参数:

$fields=implode(',', $_POST[field]);
$fd = array($fields);

print_r($fd)显示:

Array ( [0] => 'Descripción','Ocurrencias relacionadas' )

$results = $db->$table->find($param,$fd);` //This line works and returns all documents but only _id field.

有任何想法吗?快把我逼疯了!提前致谢。

4

1 回答 1

1

您以错误的方式运行查询。首先,您没有显示是什么$param,但我们假设它是一个查询,例如:

$param = array( 'field1' => 'foo' );

然后作为第二个参数,您传入一个具有两个值的数组,但这不是该方法想要的。第二个参数是要返回的字段数组,格式如下:

array( 'Descripción' => 1, 'Ocurrencias relacionadas' => 1 );

您传入以下内容:

array( 0 => 'Descripción', 1 => 'Ocurrencias relacionadas');

这意味着只显示名称为 0 和 1 的字段(可能不存在)。该_id字段始终返回,这就是它出现的原因。

您需要做的是将字段名称作为第二个参数中的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);
于 2013-07-03T08:43:21.460 回答