使用 mongoDB Jenssegers Laravel 运行原始查询

Man*_*far 4 php mongodb laravel

我正在尝试将以下 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 }});
})
Run Code Online (Sandbox Code Playgroud)

我只想运行这个简单的查询,因为它是从数据库中删除重复项。

我尝试使用如下:

Users::raw()->find('mongo raw statement')
Run Code Online (Sandbox Code Playgroud)

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

谢谢

小智 5

这是我使用 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
                ]
            ]
        ]
    ]);
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。


小智 2

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