0

I have the following user document config in yml mapping with id field as MongoId. I have use case that is required me to use aggregation builder to project data. When the result is available, the document _id will return as MongoId Object.

Does anyone know how to project the _id field in the to return string instead of MongoId?

Document mapping in YML:

UserDocument:
    fields:
        _id:
            id: true
        username:
            type: string

Aggregation Query:

$ab = $dm->createAggregationBuilder('UserDocument');
$ab->project()
   ->includeFields([
       'username',
   ]);
$users = $ab->execute();

Result:

{
  "_id": [],
  "username": "user"
}

Thanks

Billiam
  • 34
  • 4
  • I have mistaken the _id field is return as a MongoId object, I would like it to be a string instead. Thanks again. – Billiam Mar 27 '17 at 15:37

1 Answers1

0

Assuming you are json_encode()ing the result? The reason it shows up as an empty array is due to how json_encode serializes objects.

If you aren't using something like JMS to serialize your output you would need to manually coerce the type of that field. The simplest solution would be to iterate over your results and set the value to the stringified version:

foreach ($results as &$v) { $v['_id'] = (string) $v['_id']; }

By default when you use the $project operator the _id field is included unless you exclude it.

solocommand
  • 328
  • 1
  • 10
  • Thanks for the answer. I was looking for a way to build aggregation builder to return id as string. After doing more research, there is no way with the current mongodb version. – Billiam Apr 28 '17 at 16:28