mongodb get _id as string in find query

后端 未结 3 2122
死守一世寂寞
死守一世寂寞 2020-12-03 18:48

Here I have created a collection with a single document

db.getCollection(\'example\').insert({\"example\":1});

I have tried to use Projecti

3条回答
  •  孤城傲影
    2020-12-03 19:12

    One simple solution for traversing MongoCursor on PHP side is to use Generators as well as foreach or array_map($function, iterator_to_array($cursor)). Example:

    function map_traversable(callable $mapper, \Traversable $iterator) {
        foreach($iterator as $val) {
            yield $mapper($val);
        }
    }
    

    You can meet more at PHP documentation about generators syntax.

    So, now you can use/reuse it (or similar implementation) for any propose of "projecting" your data on PHP side with any amount of mapping (just like pipeline does in aggregate) but with fewer iterations amount. And this solution is pretty convenient for OOP in a case of reusing your map functions.

    UPD: Just for your case example below:

    $cursor = $db->getCollection('example')->find(["example":1],["_id":1]);
    $mapper = function($record) {
        return array('id' => (string) $record['_id']); //see \MongoId::__toString()
    }
    $traversableWithIdAsStringApplied = map_traversable($mapper, $cursor);
    //...
    

    now you can proceed with more mappings applied to $traversableWithIdAsStringApplied or use just iterator_to_array for simple array retrieving.

提交回复
热议问题