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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With