search
Homephp教程PHP开发Mongodb group operation example in PHP

Following the previous article, this article mainly talks about the group function of mongodb, which is quite powerful. It is quite complicated to use find(), skip(), distinct(), etc.

Test data:

> db.fruit.find();  
{ "_id" : 1, "category" : "fruit", "name" : "apple" }  
{ "_id" : 2, "category" : "fruit", "name" : "peach" }  
{ "_id" : 3, "category" : "fruit", "name" : "banana" }  
{ "_id" : 4, "category" : "veggie", "name" : "corn" }  
{ "_id" : 5, "category" : "veggie", "name" : "broccoli" }

1. Group according to category

> db.fruit.group(  
       {  
         key: { category: 1},  
         reduce: function(obj, prev) {  
                     prev.items.push(obj.name);  
                 },  
         initial: { items : [] }  
       }  
    );  
[  
        {  
                "category" : "fruit",  
                "items" : [  
                        "apple",  
                        "peach",  
                        "banana"  
                ]  
        },  
        {  
                "category" : "veggie",  
                "items" : [  
                        "corn",  
                        "broccoli"  
                ]  
        }  
]

php code is as follows:

$keys = array("category" => 1);  
$initial = array("items" => array());  
$reduce = "function (obj, prev) { prev.items.push(obj.name); }";  
$g = $collection->group($keys, $initial, $reduce);  
  
print_r($g);   //结果如下。  
  
Array  
(  
    [retval] => Array  
        (  
            [0] => Array  
                (  
                    [category] => fruit  
                    [items] => Array  
                        (  
                            [0] => apple  
                            [1] => peach  
                            [2] => banana  
                        )  
  
                )  
  
            [1] => Array  
                (  
                    [category] => veggie  
                    [items] => Array  
                        (  
                            [0] => corn  
                            [1] => broccoli  
                        )  
  
                )  
  
        )  
  
    [count] => 5  
    [keys] => 2  
    [ok] => 1  
)

2. Group according to category and count

> db.fruit.group(  
           {  
             key: { category: 1},  
             cond: { _id: { $gt: 2 } },  
             reduce: function(obj, prev) {  
                prev.items.push(obj.name);  
                prev.count++;  
             },  
             initial: { items : [] ,count:0}  
           }  
        );  
[  
    {  
        "category" : "fruit",  
        "items" : [  
            "banana"  
        ],  
        "count" : 1  
    },  
    {  
        "category" : "veggie",  
        "items" : [  
            "corn",  
            "broccoli"  
        ],  
        "count" : 2  
    }  
]

php code as follows:

$keys = array("category" => 1);  
$initial = array("items" => array(),'count'=>0);  
$reduce = "function (obj, prev) { " .  
              "prev.items.push(obj.name); " .  
              "prev.count++;" .  
          "}";  
$condition = array('condition' => array("_id" => array( '$gt' => 2)));  
$g = $collection->group($keys, $initial, $reduce, $condition);  
  
print_r($g);   //结果如下。  
  
Array  
(  
    [retval] => Array  
        (  
            [0] => Array  
                (  
                    [category] => fruit  
                    [items] => Array  
                        (  
                            [0] => banana  
                        )  
  
                    [count] => 1  
                )  
  
            [1] => Array  
                (  
                    [category] => veggie  
                    [items] => Array  
                        (  
                            [0] => corn  
                            [1] => broccoli  
                        )  
  
                    [count] => 2  
                )  
        )  
  
    [count] => 3  
    [keys] => 2  
    [ok] => 1  
)

3. Use aggregate group function, It’s also quite powerful

> db.fruit.aggregate([  
                     { $match: { _id: {$gt:0} } },  
                     { $group: { _id: "$category", count: { $sum: 1 } } },  
                     { $sort: { count: -1 } }  
                   ]);  
{ "_id" : "fruit", "count" : 3 }  
{ "_id" : "veggie", "count" : 2 }

The PHP code is as follows:

$cond = array(  
    array(  
        '$match' => array('_id' => array('$gt' => 0)),  
    ),  
    array(  
        '$group' => array(  
            '_id' => '$category',  
           'count' => array('$sum' => 1),  
        ),  
    ),  
    array(  
        '$sort' => array("count" => -1),  
    ),  
);  
$result = $collection->aggregate($cond);  
print_r($result);    //结果如下:  
  
Array  
(  
    [result] => Array  
        (  
            [0] => Array  
                (  
                    [_id] => fruit  
                    [count] => 3  
                )  
  
            [1] => Array  
                (  
                    [_id] => veggie  
                    [count] => 2  
                )  
  
        )  
  
    [ok] => 1  
)

Mongodb has many select operations. Here, I only talk about some commonly used functions.

For more articles related to mongodb group operation examples in PHP, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor