How to aggregate data in MongoDB using PHP?

by dalton_moen , in category: PHP Databases , 2 years ago

How to aggregate data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 2 years ago

@dalton_moen 

To aggregate data in MongoDB using PHP, you can make use of the aggregate method provided by the MongoDB PHP driver. 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
23
24
25
26
27
28
// create a new MongoDB connection
$mongo = new MongoDBDriverManager("mongodb://localhost:27017");

// specify the collection to aggregate
$collection = "mycollection";

// create the pipeline to aggregate data
$pipeline = array(
    array(
        '$group' => array(
            '_id' => '$category',
            'total' => array('$sum' => '$value')
        )
    )
);

// create the command to aggregate data
$command = new MongoDBDriverCommand(array(
    'aggregate' => $collection,
    'pipeline' => $pipeline,
));

// execute the command and retrieve the results
$cursor = $mongo->executeCommand('mydatabase', $command);
$result = current($cursor->toArray());

// output the results
print_r($result);


In this example, we are connecting to a MongoDB server running on localhost, specifying the collection to aggregate as mycollection, and creating a pipeline to group data by category and calculate the sum of the value field for each group. We then create a command to execute the aggregation pipeline, and retrieve the results using the executeCommand method. Finally, we output the results to the screen using print_r.


Note that the above code is just an example, and you may need to modify it to suit your specific use case. You can find more information on the aggregate method and aggregation pipelines in the MongoDB PHP driver documentation.