Search code examples
phpmongodblookupaggregationparse-server

Parse Server Aggregation using PHP SDK


I'm trying to build an aggregation query in Parse's PHP SDK, and I'm stuck in the "lookup" area, I saw a JS example regarding this but it doesn't work in my case.

I have a table of users, which contains a "Tags" field of type Array, the array is actually an array of pointers, that point to a separate Tag class.

What I'm trying to achieve is to list most popular Tags based on their usage, so basically I need to query the users class and group the Tags that exist in the array, I already achieved this, but I'm stuck with the lookup part, the query currently returns an array of Tags pointers, what I want is to pull the object of those pointers.

Here's what I have currently:

$query = new ParseQuery('_User');
$pipeline = [
    'project' => ['tags' => 1],
    'unwind' => '$tags',
    'group' => [
        'objectId' => '$tags.objectId',
        'count' => ['$sum' => 1]
    ],
    'sort' => [ 'count' => -1],
    'limit' => 10,
];
try {
    return $query->aggregate($pipeline);
} catch (ParseException $ex) {
    return $ex->getMessage();
}

And here's a snippet of what the _User collection looks like:

{ 
    "_id" : "5BuBVo2GD0", 
    "email" : "test@test.com", 
    "username" : "test@test.com", 
    "lastname" : "Doe", 
    "firstname" : "John", 
    "_created_at" : ISODate("2017-01-23T09:20:11.483+0000"), 
    "_updated_at" : ISODate("2019-02-15T02:48:30.684+0000"), 
    "tags" : [
        {
            "__type" : "Pointer", 
            "className" : "Tag", 
            "objectId" : "St2gzaFnTr"
        }, 
        {
            "__type" : "Pointer", 
            "className" : "Tag", 
            "objectId" : "LSVxAy2o74"
        }
    ], 
    "_p_country" : "Country$4SE8J4HRBi", 
}

And the Tag collection looks like this:

{ 
    "_id" : "St2gzaFnTr", 
    "name" : "Music", 
    "_created_at" : ISODate("2018-10-22T20:00:10.481+0000"), 
    "_updated_at" : ISODate("2018-10-22T20:00:10.481+0000")
}

Any help would be appreciated!

Thanks in advance


Solution

  • Not sure if this is a direct answer, but here's a working aggregation on tags sorting for freq...

    public function tagHistogram(Request $request, Response $response, array $args): Response {
            $pipeline = [
                 'unwind' => '$tags' ,
                 'sortByCount' => '$tags',
                 'limit' => 1000,
            ];
    
            $query = new ParseQuery('Product');
            $result = $query->aggregate($pipeline);
            $result = array_map(
                function ($e) {
                    $e['name'] = $e['objectId'];
                    unset($e['objectId']);
                    return $e;
                },
                $result
            );
    
            return $response->withJson($result);
        }