在PHP中访问MongoDB对象的属性

时间:2016-06-22 16:56:56

标签: php arrays mongodb object

最终我试图从下面的MongoDB对象访问customer_id属性。我可以通过首先转换为数组来实现这一目的:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [ "customer_id" => ['$eq' => '1001']];
$query = new MongoDB\Driver\Query($filter);
$cursor = $manager->executeQuery('srp.products', $query);
$cursor = $cursor->toArray();
print_r ($cursor[0]->customer_id);

但我无法使用以下方式访问它:

$cursor->cursor['current_doc']->customer_id

我是否总是需要先转换为数组,或者我错过了什么?

MongoDB\Driver\Cursor Object
(
    [cursor] => Array
        (
            [stamp] => 0
            [is_command] => 
            [sent] => 1
            [done] => 
            [end_of_event] => 
            [in_exhaust] => 
            [has_fields] => 
            [query] => stdClass Object
                (
                    [find] => products
                    [filter] => stdClass Object
                        (
                            [customer_id] => stdClass Object
                                (
                                    [$eq] => 1001
                                )

                        )

                )

            [fields] => stdClass Object
                (
                )

            [read_preference] => Array
                (
                    [mode] => 1
                    [tags] => Array
                        (
                        )

                )

            [flags] => 0
            [skip] => 0
            [limit] => 0
            [count] => 1
            [batch_size] => 0
            [ns] => srp.products
            [current_doc] => stdClass Object
                (
                    [_id] => MongoDB\BSON\ObjectID Object
                        (
                            [oid] => 576aa3469771c4dbeef44022
                        )

                    [customer_id] => 1001
                    [products] => Array
                        (
                            [0] => 150
                            [1] => 160
                            [2] => 170
                            [3] => 180
                        )

                )

        )

    [server_id] => 1
)

1 个答案:

答案 0 :(得分:0)

是的,你应该像你一样拨打->toArray(),或者foreach通过Cursor获得结果。有关Cursor中可用内容的更多信息,请docs