MongoDB:ObjectId到String

时间:2011-11-12 18:17:45

标签: php mongodb

大家好我使用MongoDB find()方法:

$cursor = $collection->find();
foreach($cursor as $doc) {
   // do something....
}

没关系,但是我的_id属性是自动生成的,所以当我使用上面的代码时,$ doc [_id]是Object,但我需要一个字符串。

如何自动将其转换为字符串。不是这样的:

foreach($cursor as $doc) {      
    $doc['_id'] = (string)$doc['_id'];
}

3 个答案:

答案 0 :(得分:2)

json_encode曾经a bug in the php driver正确处理mongoid。它应该从v1.0.11开始修复。

答案 1 :(得分:1)

要从MongoDB驱动程序的任何结果自动将ObjectId转换为字符串,我使用此函数:

function convertMongoIds(array &$array){
    foreach ($array as &$element){
        if (is_array($element)){
            convertMongoIds($element);
        }else if (is_object($element) && get_class($element) == "MongoId"){
            $element = (string) $element;
        }
    }
}

答案 2 :(得分:0)

`$result = $collection->findOne([
     '_id' => new \MongoDB\BSON\ObjectId("5a59b11b3ffd3aec4a23cd2c")
]);


var_dump((string)$result->_id, $result->_id->__toString());`

两者都适用于版本3.6。

reference