How to group data in MongoDB using PHP?

by ryan.murray , in category: PHP Databases , 2 years ago

How to group data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a year ago

@ryan.murray 

To group data in MongoDB using PHP, you can use the aggregate() function of the MongoDBDriverManager class. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Set up MongoDB connection
$manager = new MongoDBDriverManager("mongodb://localhost:27017");

// Set up aggregation pipeline
$pipeline = [
    ['$group' => [
        '_id' => '$category',
        'count' => ['$sum' => 1]
    ]]
];

// Execute aggregation pipeline
$command = new MongoDBDriverCommand([
    'aggregate' => 'products',
    'pipeline' => $pipeline
]);
$cursor = $manager->executeCommand('database_name', $command);

// Iterate over the results
foreach ($cursor as $document) {
    var_dump($document);
}


In this example, the aggregate() function is used to group data by the category field of the products collection, and count the number of documents in each group. The resulting documents are returned in the $cursor object, which can be iterated over to access the individual documents.


The $group stage in the aggregation pipeline specifies the _id field as the category field, and uses the $sum accumulator operator to count the number of documents in each group.