简体   繁体   中英

Doctrine mongodb-odm aggregation builder query with ObjectId

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM