sandip kakade
sandip kakade

Reputation: 1356

How to implement MongoDB query in Laravel 5?

I created mongodb query which I have to use in laravel controller.

My query is

db.PMS.aggregate([
    { $match: { "PanelID": "A00898" } },
    { 
        $project: { EventTS: 1, MainsPower: 1, } 
    },
    {
        $unwind: {
            path: "$MainsPower",
            includeArrayIndex: "arrayIndex",
            preserveNullAndEmptyArrays: true
        }
    },
    {
        $project: {
            MainsPower: 1,
            timestamp: {
                "$add": [
                    "$EventTS",
                    { "$multiply": [ 60000, "$arrayIndex" ] }
                ]
            }
        }
    }
]);

I tried to use this query in a laravel function but I am little confused. Please help me how to implement this query in laravel.

Upvotes: 1

Views: 689

Answers (1)

chridam
chridam

Reputation: 103365

Perform raw expressions on the internal MongoCollection object to run the aggregation:

$result = DB => collection('PMS')->raw(function ($collection){
    return $collection->aggregate(array(
        array( '$match' => array( "PanelID" => "A00898" ) ),
        array( '$project' => array( 'EventTS' => 1, 'MainsPower' => 1 ) ),
        array(
            '$unwind' => array(
                'path' => "$MainsPower",
                'includeArrayIndex' => "arrayIndex",
                'preserveNullAndEmptyArrays' => true
            )
        ),
        array(
            '$project' => array(
                '_id' => 0,
                'MainsPower' => 1,
                'timestamp' => array(
                    "$add" => array(
                        "$EventTS",
                        array( "$multiply" => array( 60000, "$arrayIndex" ) )
                    )
                )
            )
        )
    ));
});

Upvotes: 1

Related Questions