mydb
mydb

Reputation: 45

MongoDB - PHP Group By Count

I have this code :

$data=$collection1->aggregate(array( '$group'=> array('_id'=>$valoreScelto,'contatore'=>array('$sum'=>1))));

$valoreScelto is a valid field of document MongoDB, that i retry by FORM.

$valoreScelto = trim('$'.$campoSelezionato);

I obtain this error:

Fatal error: Call to a member function aggregate() on string

Upvotes: 1

Views: 5857

Answers (2)

sameera sy
sameera sy

Reputation: 1718

I tried the above answer as well and it wasn't returning anything. After a lot of trying I figured out that I had missed a keyword without which the above query was not going to work. I am pasting the code below.

$ops = [
    [
        '$group' => [
            "_id" => $valoreScelto,
            "contatore"   => ['$sum'=>1],
        ]
    ]
 ];
$data=$collection1->aggregate($ops)->toArray();

Upvotes: 0

Maxim Tkach
Maxim Tkach

Reputation: 1697

UPDATE:

The error says: You are trying to access the method "aggregate", in the string (Variable $collection1 have type - string).

You need to check $collection1 (for example var_dump). $collection1 must be Collection (or in mongo extension MongoCollection).

You can get a collection like this:

   $yourConnectInDB = new Client(...); // or MongoClient(...);
   $db = $yourConnectInDB->selectDatabase('YOUR DB NAME');
   $collection1 = $db->selectCollection('YOUR COLLECTION NAME');

Also, in your code you want to use the aggregation like this:

$ops = array( // base array
    array(
        '$group' => array(
            "_id" => $valoreScelto,
            "contatore"   => array('$sum'=>1),
        )
    ),
   // other pipeline
);
$data=$collection1->aggregate($ops);

Read this and this

Upvotes: 1

Related Questions