mongodb限制字段返回PHP


mongodb limit the fields to return PHP

我有一个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.

有什么想法吗?它把我逼疯了!提前谢谢。

您以错误的方式运行查询。首先,您没有显示$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);