MongoDB:ObjectId 转为字符串

4
大家好,我使用MongoDB的find()方法,如下所示:

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

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

如何自动将其转换为字符串,而不是像这样:

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

2
为什么需要它成为一个字符串?在大多数需要字符串的情况下(例如echo等),对象的__toString()将自动调用。无论如何,不要使用字符串覆盖$doc对象的_id - salathe
@user1006884:实际上,强制类型转换应该可以。问题出在哪里? - netcoder
我使用这个:json_encode($doc); 所以我不会使用echo。 - Erik
3个回答

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


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

两者在版本3.6中均可使用。

参考链接


3
为了从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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接