0

If document has fields with value as MongoId object, it will be returned to php something like http://dl.dropbox.com/u/7017985/Screenshots/26.jpg, is there any way how to return it like simple strings and not as MongoId object.

Why I need it ? Because I need to send result to javascript browser side. I have document which has 2-3 fields which is refs to another document, and they keep as ObjectId.

4

4 回答 4

0

我需要 MongoIds 对 javascript/json(客户端)友好,所以我想透明地转换多个 mongoIds。我找不到任何内置功能来实现这一点,但想出了以下解决方案:

<?php
function strToMongoIdObj(Array $_ids) {
    return array_map(function($id) {
            return new MongoId($id);
        }, $_ids);
}

function mongoIdToStr(MongoCursor $cursor) {
    $rs = array();
    foreach ($cursor as $doc) {
        $doc['_id'] = (string)$doc['_id'];
        $rs[] = $doc;
    }
    return $rs;
}

$_ids = array("522dbdd29076fde9057bb5ed",
              "522dbf229076fdeb053f5b7b");

$m = new MongoClient();
$cursor = $m->db->col
    ->find(array('_id' => array('$in' => strToMongoIdObj($_ids))));

print_r(mongoIdToStr($cursor));
于 2013-09-10T08:38:03.053 回答
0

MongoID 支持__toString. 如果将其转换为字符串,或__toString直接调用,它会将值转换为字符串。

于 2013-04-14T20:02:00.500 回答
0

您可以遍历查询结果并将所有 MongoId 对象转换为字符串。如果给定来自 MongoCollection::findOne() 的单个结果数组或来自 MongoCollection::find() 的 MongoCursor 结果,则以下函数将转换所有 id。

function convert_mongoid_to_string(& $mongo_object)
{
    foreach($mongo_object as $mongo_key=>$mongo_element)
    {
        if(is_array($mongo_element)||is_object($mongo_element))
        {
            if(get_class($mongo_element) === "MongoId")
            {
                 //cast the object to the original object passed by reference
                 $mongo_object[$mongo_key]=(string)$mongo_element;
            }
            else
            {
                //recursively dig deeper into object looking for MongoId's
                convert_mongoid_to_string($mongo_element);
            }
        }
        else
        {
            //is scalar so just continue
            continue;
        }
    }
    return $mongo_object;
}
于 2013-04-23T20:39:58.880 回答
0

我不相信有。

MongoDB 以 BSON 文档的形式输入和输出,其ObjectId字段采用这种特定格式。

这是你无法改变的。

于 2013-04-23T16:49:46.967 回答