使用 mongoDB Jenssegers Laravel 运行原始查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40619898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Raw Query using mongoDB Jenssegers Laravel
提问by Mansoor Jafar
I am trying to use following mongoDB query with Laravel Jessanger, but could not run it as raw
query.
我正在尝试将以下 mongoDB 查询与Laravel Jessanger一起使用,但无法将其作为raw
查询运行。
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
谢谢
回答by Mursaleen Momin Raush
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:
这是我使用 Mongodb (Laravel Jensseger) 的第一天,我很幸运能够弄清楚。所以,我想查询我的 Messages 模型:
// 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.
希望这可以帮助。
回答by LynX
In the Laravel Jenssegers Library in a section Raw Expressionsis described want to create a raw expression. The raw expression accept an array object of condition. In your example the find method isn't right.
在 Laravel Jenssegers Library 的Raw Expressions一节中,描述了想要创建一个原始表达式。原始表达式接受条件数组对象。在您的示例中, find 方法不正确。