1

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.

1 Answer 1

1

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" ) )
                    )
                )
            )
        )
    ));
});
Sign up to request clarification or add additional context in comments.

4 Comments

query output in object format how to convert in to array
@dhanashri Since the original problem is solved, can you create a new question for this issue please?
ok but last question related to this question i want remove _id, So where i put _id:0 please suggest me... @chridam
@dhanashri Again, this is considered bad practice as chameleon questions are not encouraged here on SO. Notwithstanding this, I have updated the answer to include how you can remove the _id field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.