Search code examples
mongodbphp-mongodb

PHP mongo filter subdocument


I want to use an aggregator for filtering the subdocument. I want to show only 25 elements in "Message" subdocument matching sType ="xdc" only and search in "type". It should not shown others soubdocument other than match.

[0] => Array(
 [_id] => MongoDB\BSON\ObjectId Object([oid] => 638ec2add00b0e7ac9225506)
 [id] => 80269
 [cd] => 2388     
 [messages] => [0] => Array 
                (
                    [type] => gmail
                    [time] => 07.09.2022 08:52:02                     
                    [sType] => game
                )
               [1] =>[0] => Array 
                (
                    [type] => gmail
                    [time] => 07.09.2022 08:52:02                     
                    [sType] => game
                )
  )

[1] => Array(
 [_id] => MongoDB\BSON\ObjectId Object([oid] => 639ec2add00b0e7ac9225506)
 [id] => 80267
 [cd] => 2388
      [messages] => [0] => Array 
                (
                    [type] => yahoo
                    [time] => 07.09.2022 08:52:02                     
                    [sType] => invest
                )
                   [1] =>[0] => Array 
                (
                    [type] => opera
                    [time] => 07.09.2022 08:52:02                     
                    [sType] => xdc
                )
  )

I am trying to use an aggregator for filter but getting a single array in a message.I

    $where["contactus_id"] = $cust_id; 
    $pipeline = [
        ['$match' => $where],
        ['$unwind' => '$messages'],
        ['$match' => ["messages.RequestType" => $type]],
        ['$limit' => $limit],
        ['$sort' => ['id' => -1]],
    ];
 $result = $collection->aggregate($pipeline, $option);

Solution

  • I was able to filter subdocument and removed the unwanted subdocument items using $addfields

    $where["messages.type"] = $type;
    $pipeline =[
                    ['$match' => $where],
                    ['$addFields' => [
                                        'messages'=> [
                                                        '$filter'=> [
                                                                        "input"=> '$messages',
                                                                        "as"=> "d",
                                                                        "cond" => ['$eq' => ['$$d.type', $type]]
                                                                    ]
                                                    ]
                                        ]
                    ],
                    ['$limit' => $limit],
                    ['$sort' => ['id' => -1]],
                ];