0

I'm trying to get users posts with mongodb in laravel, this query is working fine in mongodb shell but it's not working in laravel and it gives me this error :

A pipeline stage specification object must contain exactly one field.

this is my query in mongodb shell :

db.instaPosts.aggregate([ 
 {"$match" :{ "userid" : "1507073550"}}, 

{"$group" : 
{ "_id" : "$post.location.id", 
"location" : {"$first":"$post.location.name"},

"count":{ "$sum" : 1}}} 
])

and this the results :

{ "_id" : null, "location" : null, "count" : 7 }
{ "_id" : "332558707", "location" : "Daryache Chitgar,Tehran,Iran", "count" : 1 }
{ "_id" : "250445386", "location" : "دانشگاه علم و فرهنگ", "count" : 1 }
{ "_id" : "1343757649052341", "location" : "Agor Caffe", "count" : 1 }
{ "_id" : "111106416225578", "location" : "Santiago Bernabeu, Madrid", "count" : 1 }
{ "_id" : "506047058", "location" : "Cardiff City Stadium", "count" : 1 }

and this is my controller :

        $places = Posts::raw(function ($collection){
            return $collection->aggregate([
               [
                   '$match' => [
                           'userid' => [ '$eq' => '1507073550']
                   ],
                    '$group'=> [
                        '_id' => '$post.location.id',
                        'location' => [
                            '$first'=>'$post.location.name'
                        ],
                        'total' => [
                            '$sum' => 1
                        ],
                    ]
               ]
            ]);
        });

exact same things! but it's not working.

1 Answer 1

1

Finally found the solution!

        $places = Posts::raw(function ($collection){
            return $collection->aggregate([
               [
                   [
                   '$match' => [
                           'userid' => [ '$eq' => '1507073550']
                      ],
                   ],
                   [
                    '$group'=> [
                        '_id' => '$post.location.id',
                        'location' => [
                            '$first'=>'$post.location.name'
                        ],
                        'total' => [
                            '$sum' => 1
                        ],
                      ]
                   ]
               ]
            ]);
        });

I should've wrap $match and $group with [] ,

Sign up to request clarification or add additional context in comments.

1 Comment

one external [] should be removed. '$match' should be before '$group' it's important !!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.