我有一个PHP脚本,它从MongoDB收集数据并打印出来。一些选项是从$_POST
supergoblal收集的。一切正常但我无法限制使用数组返回的字段。
$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.
有什么想法吗?这让我很生气! 提前谢谢。
答案 0 :(得分: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);