Select * group by in mongo aggregation

后端 未结 4 1429
名媛妹妹
名媛妹妹 2021-02-08 02:25

I am trying to do something that I think is quite simple. Suppose I have a series of records in mongo that have a common key, and variable number of attributes. I want to select

4条回答
  •  清歌不尽
    2021-02-08 03:04

    Here is the another way of doing it :

    $connection = 'mongodb://localhost:27017';
    $con        = new Mongo($connection); // mongo connection
    
    $db         = $con->test; /// database
    $collection = $db->prb; // table
    
    $keys       = array("Name" => 1,"x"=>1,"y"=>1,"z"=>1);
    
    // set intial values
    $initial    = array("count" => 0);
    
    // JavaScript function to perform
    $reduce     = "function (obj, prev) { prev.count++; }";
    
    $g          = $collection->group($keys, $initial, $reduce);
    
    echo "
    ";
    print_r($g);
    

    You will get the answer something like this (not the exact output) :

    Array
    (
        [retval] => Array
            (
                [0] => Array
                    (
                        [Name] => George
                        [x] => 
                        [y] =>
                        [z] =>
                        [count] => 2
                    )
    
                [1] => Array
                    (
                        [Name] => Rob
                        [x] => 
                        [y] =>
                        [z] =>
                        [count] => 1
                    )
    
            )
    
        [count] => 5
        [keys] => 3
        [ok] => 1
    )
    

提交回复
热议问题