MongoDB将ObjectId转换为结果中的字符串

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.

MongoID supports __toString. If you cast it as a string, or call __toString directly, it will convert the value to a string.

I do not believe there is.

MongoDB takes input and output in the form of BSON documents whose ObjectId field takes this particular formation.

This is something you cannot change.

You could loop through the query results and convert all MongoId objects to strings. The below function will convert all ids if given either a single result array from MongoCollection::findOne(), or a MongoCursor result from MongoCollection::find().

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;
}

I've needed the MongoIds to be javascript/json (client side) friendly so I wanted to convert multiple mongoIds transparently. I couldn't find any build-in functionality to achieve this, but came up with the following solution:

<?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));