使用Jenssegers Laravel运行MongoDB的原始查询

5

我正在尝试使用以下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 }});
})

我希望直接运行这个查询以从数据库中删除重复项。

我尝试使用以下方式:

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

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

谢谢


我有你的问题,你解决了吗? - Mohammad_Hosseini
2个回答

8

这是我使用Mongodb (Laravel Jensseger)的第一天,我很幸运地理解了它。所以,我想查询我的消息模型:

// 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
                ]
            ]
        ]
    ]);
});

希望这可以帮助你。

2
在Laravel Jenssegers库的一个部分原始表达式中,描述了如何创建原始表达式。原始表达式接受一个条件数组对象。在您的示例中,“find”方法不正确。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接