Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Raw Query using mongoDB Jenssegers Laravel

I am trying to use following mongoDB query with Laravel Jessanger, but could not run it as raw query.

db.getCollection('users').aggregate([
    { 
        "$group": { 
            "_id": { "cnic": "$cnic", "time_in": "$time_in" }, 
            "uniqueIds": { "$addToSet": "$_id" },
            "count": { "$sum": 1 } 
        }
    }, 
    { "$match": { "count": { "$gt": 1 } } }
]).forEach(function(doc) {
    doc.uniqueIds.shift();
    db.getCollection('users').remove({_id : {$in: doc.uniqueIds }});
})

I want to just run this plain query as it is to remove duplicates from the database.

I tried to use like following:

Users::raw()->find('mongo raw statement')

and

$cursor = DB::collection('users')->raw(function($collection)
{
    return $collection->find('mongo raw statement');
});

Thanks

like image 284
Mansoor Jafar Avatar asked Jan 06 '23 01:01

Mansoor Jafar


1 Answers

This is my first day with Mongodb (Laravel Jensseger), and I was lucky enough to figure it out. So, I wanted to query my Messages model:

// This is the SQL version
$unreadMessageCount = Message::selectRaw('from_id as sender_id, count(from_id) as messages_count')
   ->where('to_id', auth()->id())
   ->where('read', false)
   ->groupBy('from')
   ->get();

// This is the Mongo version. The solution was figuring out the 'aggregate' concept in Mongo
$unreadMessageCount = Message::raw(function($collection)
{
    return $collection->aggregate([
    [
      '$match' => [
        'to_id' => auth()->id()
      ]
    ],
        [
            '$group' => [
                '_id' => '$from_id',
                'messages_count' => [
                    '$sum' => 1
                ]
            ]
        ]
    ]);
});

Hope this helps.

like image 107
Raush Avatar answered Jan 13 '23 09:01

Raush