dongyi7513 2013-07-02 22:02 采纳率: 100%
浏览 28

mongodb限制字段返回PHP

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.

  • 写回答

1条回答 默认 最新

  • douyin2883 2013-07-03 08:43
    关注

    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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题